How does this code compile to gcc and what does it actually do?
In my work, someone produced a code that decreases like this:
int main()
{
int a[20];
a[3, 4];
return 0;
}
a [3, 4] compiles without error and without warning by default gcc. The following warning is issued with the gcc -Wall option:
test.c: In function ‘main’:
test.c:4:8: warning: left-hand operand of comma expression has no effect [-Wunused-value]
a[3, 4];
^
test.c:4:5: warning: statement with no effect [-Wunused-value]
a[3, 4];
^
I can also compile clang.
Basically, I don't understand why this compiles? And what does it actually do (I know [3,4] returns a pointer, but that's all I understand). I tried to look at the assembly code with the -S gcc option, but I really don't understand its output (no knowledge of x86 assembly).
EDIT: it doesn't actually return a pointer, but an integer (error on my part)
source to share
FIrst, the comma operator: it evaluates each part, but only "returns" the last. a[3,4]
matches a[4]
.
If 3 were a function, it would be executed without storing the return value,
but only 3 doesn't matter (nothing was done and 3 is not used): This is the first warning.
Second, an expression without any effects.
In C (etc.) you can write things like 1;
; they don't do anything other than actual (useless) code. a[4];
is not different, this is the reason for the second warning.
You probably won't find anything in the generated assembly code
(perhaps a comment with C code and line number), because there is nothing to generate at all. The compiler can generate something to load a[4]
from memory and not use it then, but this will most likely be optimized.
source to share