Interview Question
Country: United States
int a[5];
a+4; /* Good */
a+5; /* Good */
a+6; /* Bad. Undefined */
a[5]; /* Bad. Undefined*/
a[6]; /* Also Undefined */
Right?
&a[5] is equal to &*(a+5).
if '&' is followed by '*', C compiler remove them.
So &*(a+5) is equal to a+5.
It's valid.
It never deference 5th element.
Surprise, surprise, but it's 3 and 6.
Shifting something left by more than or equal to its bitwidth is undefined. An int can only be shifted 31 or less. That's assuming an int is 32 bits on your architecture, of course.
4 and 5 are actually perfectly fine because an expression like &a[i] gets translated to (a+i) without ever dereferencing that address. So we're just comparing pointers and never dereferencing them.
Yeah, 1 is also undefined. The others...I don't see how. What's their definition of undefined? I mean, a+5 could be less than a+4 if it overflows, and that's situation and architecture dependent, but I wouldn't say that's undefined.
1 is undefined . but how ??
e.g. int a[5]={0};
int i=2;
a[i]=i++;
for(i=0;i<5;i++)
printf("%d\n",a[i]);
imp thing is a[2]=2 .
6 is not undefined.
comma operator is a sequence point and that means the order of the operations inside the (++i,i++,i) is well defined. That is, the above expression can be translated to something like this, which is well defined:
++i; i++; i = i;
see this answer (it contains examples similar to 1 and 6):
stackoverflow.com/a/4176333
6 is not undefined.
comma operator is a sequence point and that means the order of the operations inside the (++i,i++,i) is well defined. That is, the above expression can be translated to something like this, which is well defined:
++i; i++; i = i;
see this answer (it contains examples similar to 1 and 6):
stackoverflow.com/a/4176333
Well 1,2,3,5 will show undefined behavior because of following reasons -
1. The unary operator ++ is always very ambiguous and it's precedence changes from machine to machine, so at a particular machine you just can't predict whether the a[i] will get the new or old value of i, thus this is undefined.
2. It will be an integer overflow. As you cannot increase the value of INT_MAX and try to print it with integer specifier, as it is the maximum value of int.
3. Here the width of int is 32 and you are shifting 1 left by >= width which will cause undefined behavior.
5. It is very obvious that you cannot use &arr[6] as it will be an address of just a random chunk of memory and it will always give an undefined result.
Do you think question 4 and 5 should be?
- Anonymous July 05, 20124. int a[5];
return (&a[5]<&a[4]);
5. int a[5];
return (&a[5]<&a[6]);