+ 2
Question is easy. Answer is not easy. Why answer is 1? (C++)
#include <iostream> using namespace std; int main() { int arr[]={0-arr[1],1-arr[2],2}; int sum =arr[0]+arr[1]+arr[2]; cout<<sum; } Answer is 1.
9 Answers
+ 7
I don't know what you expected from this code, but it's behavior is definately undefined. You're trying to use values of the array, that's being initialized with those values. So compiler is free to launch you to the moon or do any other random and unexpected thing.
But, if you want a speculation on why the result is like that, here it is (all the charachters are entirely fictional, and so on):
First of all, as the array is being initialized, the compiler defaults it's values to zeros â it's normal behavior, like with `int a[10] = {}; // Gets initialized to 0`. At least it may expect them to be 0.
Then the compiler should evaluate the values in the initializer. There's no defined order of evaluation here. No right to left or left to right. As often is observed, gcc takes a "BFS" approach to unwind the "evaluation tree". So it goes like this:
1. {0-arr[1], 1-arr[2], 2}
becomes:
2. {EVAL(0-arr[1]), EVAL(1-arr[2]), EVAL(2)}
that becomes:
3. {EVAL(EVAL(0) - EVAL(arr[1])), EVAL(EVAL(1) - EVAL(arr[2])), 2}
"2" gets evaluated first, as it's the shallowest in the evaluation tree. Anyway, this becomes:
4. {EVAL(0 - EVAL(arr[1])), EVAL(EVAL(1) - EVAL(arr[2])), 2}
then:
5. {EVAL(0 - EVAL(arr[1])), EVAL(1 - EVAL(arr[2])), 2}
and:
6. {EVAL(0 - 0), EVAL(1 - EVAL(arr[2])), 2}
arr[1] is assumed to be zero, as if we're using initializetion, all the unitialized elements default to 0. Continuing:
7. {EVAL(0 - 0), EVAL(1 - 2), 2}
"2" â because arr[2] is already known to be 2. Anyway:
8. {0, EVAL(1 - 2), 2}
and:
9. {0, -1, 2}
So, it gets initialized to {0, -1, 2}. But, according to the standard, the chances for this are the same as for getting few daemons fly out of your nose. So, I repeat, all this is pure speculation (though based on an observation).
+ 2
I've seen gcc taking this evaluation order quite a few times, in case there was no order defined by the standard. Like in function parameters evaluation, or cin/cout chain. So, even though it's undefined, I kind'a expect this order from gcc. But the part where 'arr[1] is assumed to be zero' in step 6 â that's just my guess to fit the behavior to the result. Anyway, all this is UB, and it isn't supposed to be logical.
+ 2
@kurwius, not afraid of nasal daemons? ;)
+ 1
If I set:
int arr[] = {arr[0], arr[1], arr[2]}
And then It elements separated with a "," I get:
1960210976, -1663767622, -2
I don't know what are these numbers, maybe something with the memory.
If I cout the elements of your array, It prints:
0 -1 2 , where the sum of them is 1.
I hope this can help
+ 1
@Marvin answer matches the values outputted, if you cout the array after the fact.
+ 1
@marvin, Thanks for detail explanation.