Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the printf statement in the code below printing a value rather than a garbage value?

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?

like image 208
user8635555 Avatar asked Dec 30 '25 04:12

user8635555


1 Answers

Technically speaking, this invokes undefined behaviour. Quoting C11, chapter §6.5.6

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. [....]

So, (array-2) is undefined behavior.

However, most compilers will read the indexing, and it will likely be able to nullify the +2 and -2 indexing, [2[a] is same as a[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 value array[0], and -ved.

like image 199
Sourav Ghosh Avatar answered Dec 31 '25 17:12

Sourav Ghosh