3

In my work somebody did produce a code which is reduced as follow:

int main()
{
    int a[20];
    a[3, 4];
    return 0;
}

the a[3, 4] compile without error and without warning on default gcc option. With gcc -Wall option it produce the following warning:

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 on clang.

Basically, i dont understand why this is compiling ? And what it is actually doing (i know a[3,4] return a pointer but that is all i understand). I have tried to look at the assembly code with the -S gcc option but i dont really understand its output (lack of x86 assembly knowledge).

EDIT: it actually does not return a pointer but a integer (mistake on my part)

sepp2k
  • 363,768
  • 54
  • 674
  • 675
Phong
  • 6,600
  • 4
  • 32
  • 61

2 Answers2

4

FIrst, the comma operator: It evaluates each part but "returns" only the last.
a[3,4] is the same as a[4].

If 3 were a function, it would be executed without keeping the return value,
but 3 alone is irrelevant (nothing executed and 3 not used): That´s the first warning.

Second, a expression without any effects.
In C (etc.), you can write things like 1;; they do nothing but are valid (useless) code.
a[4]; is not different, that´s the reason for the second warning.

You probably won´t find anything of it in the generated assembler code
(maybe a comment with C code and line number), because there is nothing
to generate at all. The compiler could generate something to load a[4]
from memory and don´t use it then, but that´s very likely to be optimized away.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
2

i know a[3,4] return a pointer but that is all i understand

Nope. Here are no pointers involved at all, and a[3, 4 isn't "returning" anything.

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

  • 4
    And technically pointers _are_ involved here, because `a[3,4]` is essentially syntactic sugar for `*(a+(3,4))` in this context (`a+(3,4)` most certainly being a pointer). – Lightness Races in Orbit Dec 10 '14 at 13:16