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 functionmain’:
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)

+3


source to share


2 answers


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.

+4


source


I know [3,4] is returning a pointer, but that's all I understand

Nope. There are no pointers here, and a[3, 4

it returns nothing.



3, 4

is an expression with a comma operator that evaluates to its RHS, namely 4. So the array is a

indexed with number 4.

+2


source







All Articles