int main(){
int array[] = [10,20,30,40,50] ;
printf("%d\n",-2[array -2]);
return 0 ;
}
Can anyone explain how -2[array-2] is working and Why are [ ] used here? This was a question in my assignment it gives the output " -10 " but I don't understand why?
Technically speaking, this invokes undefined behaviour. Quoting
C11, chapter §6.5.6So,
(array-2)is undefined behavior.However, most compilers will read the indexing, and it will likely be able to nullify the
+2and-2indexing, [2[a]is same asa[2]which is same as*(a+2), thus,2[a-2]is*((2)+(a-2))], and only consider the remaining expression to be evaluated, which is*(a)or,a[0].Then, check the operator precedence
-2[array -2]is effectively the same as-(array[0]). So, the result is the valuearray[0], and-ved.