tags:

views:

59

answers:

3
+1  Q: 

Confusing output?

I fail to understand is why does the code print '3' in VS2010 (release build), whether I leave the declaration of 'r' or comment it out.

int main(){
    int arr1[2];
    int &r = arr1[0];
    int arr2[2];

    cout << (&arr1[1] - &arr2[0]);
}

So, three questions:

a. why does the code print 3?

b. why does it print 3 even if the declaration of 'r' is present? (Is it because that in C++ whether a reference occupies storage or not is implementation defined?)

c. Does this code have undefined behavior or implementation defined behavior?

+3  A: 

Because in Release build r variable is removed. Unused variable of built-in type is removed, because Release build is done with optimizations. Try to use it later, and result will change. Some variables may be placed into CPU register and not on the stack, this also changes the distance between another local variables.

On the other hand, unused class instance is not removed, because class instance creation may have side effects, since constructor is invoked.

This is both undefined and implementation-defined behavior, because compiler is free to place variables in any place where it is appropriate.

Alex Farber
+2  A: 

a. Order of the variables in memory are from

arr2[0]
arr2[1]
arr1[0]
arr1[1]

the code prints 3 because its using pointer arithmetic. Subtracting &arr1[1] from &arr2[0] means a difference of 3 int's.

b. Since r is never referenced, the C++ compiler is free to optimize it out.

c. Not positive but I don't believe the C++ standard defines an explicit order to variables on a stack. Therefore the compiler is free to reorder these variables, even putting extra space between them as it see's fit. So, yes its implementation specific. A different compiler could have just as easily given -1 as the answer.

MerickOWA
A: 

&arr1[1] - &arr2[0]

Pointer arithmetic is only well-defined within the same array. It does not matter what you think this code snippet does or should do, you are invoking undefined behavior. Your program could do anything.

FredOverflow