0

What's the output of this code? ["AND WHY"]

int x = 0 ; int a [] = {3, 4} ; a [x] = ++x ; cout << a [0] ;

18th Jan 2017, 11:53 PM
Amr Monsef
Amr Monsef - avatar
10 Answers
+ 7
Oh, JavaScript is so different from C++. Thanks for correcting me, I thought the way they deal with arrays is the same. @Potto I don't know C++. I completed the course but forgot everything the next day.
19th Jan 2017, 1:28 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 4
x is 0, so a[x] is ++x which means a[0] = 1. The answer is 1.
19th Jan 2017, 1:10 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 4
@Robobrine what? How is it not like that? The answer is 1.
19th Jan 2017, 1:23 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 4
int x = 0 ; /* initializing a variable x with 0 */ int a [] = {3, 4} ; /* initializing an integer array a with the values 3 and 4. The array automatically has the length two because there are two values in the curly brackets */ a [x] = ++x ; /* see my other comment, x[0] is the first value in the array (3), a[1] the second (4) */ cout << a [0] ; /* gives out the first value of the array */
19th Jan 2017, 1:31 AM
Robobrine
Robobrine - avatar
+ 3
The programm looks at the whole line: a[x] = ++x; First thing it does is the ++x. x was 0 before, so the line above turns into: a[1] = 1; a[0] doesn't change and stays 3.
19th Jan 2017, 12:36 AM
Robobrine
Robobrine - avatar
+ 1
Robobrine is right. Run it through your compiler, cheeze!
19th Jan 2017, 1:26 AM
Potto
Potto - avatar
0
cheeze that's not how it works...
19th Jan 2017, 1:20 AM
Robobrine
Robobrine - avatar
0
guys I'm so sorry can anyone explain the code line by line for am so confused with "arrays" specialy when I put the variable
19th Jan 2017, 1:20 AM
Amr Monsef
Amr Monsef - avatar
0
when put the variable x into the [] of the array
19th Jan 2017, 1:20 AM
Amr Monsef
Amr Monsef - avatar
0
@cheeze the code doesn't get executed left to right, it will first calculate ++x and then look at the rest, so you have a[1] = 1; not a[0] = 1;
19th Jan 2017, 1:25 AM
Robobrine
Robobrine - avatar