4

I'm studying C and I came across the code below. The printed results are always the same for all the printf calls.

What does [x,y] mean? A memory address or something else?

printf("%d ", array[0,0]);
printf("%d ", array[1,0]);
printf("%d ", array[2,0]);
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
A.Sim
  • 91
  • 1
  • 10
  • 5
    Two words: comma operator. Many words: the subscript expression contains a comma operator which evaluates the LHS (0 or 1 or 2) and discards that, then evaluates the RHS (always 0) and that is used as the subscript into the array, so you always get the same value printed — `array[0]`. And if `array` is actually a 2D array of some sort, then `array[0]` will be an address rather than a simple integer value. A good compiler would generate several warnings per line — find the options to convert your compiler into a good compiler, or get good compiler. – Jonathan Leffler May 11 '19 at 22:16
  • 1
    The comma operator discards the result of the left side. `array[0,0]` is the same as `array[0]`. – Elan Hamburger May 11 '19 at 22:18
  • 5
    Three words: don't do that. – user3386109 May 11 '19 at 22:19
  • 2
    I imagine your compiler gives you warning about this if you use them as you should. With `gcc`, I use `-Wall -Wextra -pedantic`, though there might be better choices. – ikegami May 11 '19 at 22:23

2 Answers2

11

The comma operator in returns the second argument. So 0,0, 1,0, and 2,0 all evaluate to 0, so its no wonder that all the printf statements print the same result. If you want to refer to an element in a two-dimensional array by its indexes, you need to use two sets of square bracket. E.g., array[1][0].

Mureinik
  • 297,002
  • 52
  • 306
  • 350
7

It's a 'comma operator'. In C, a comma operator evaluates each argument but returns the rightmost argument. So array[0,1] is as same as array[1] and array[0,1,2]is as same as array[2]. In your case array[0,0]), array[1,0], array[2,0] all evaluate array[0]. So all the statements print the same result.

Additionally (from @chqrlie's comment), though it returns the rightmost argument, all the expressions are evaluated so any side effects are performed: printf("%d ", array[exit(1),0]); will not print anything.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Niloy Rashid
  • 687
  • 4
  • 16
  • 3
    You might add a note about all expressions getting evaluated so any side effects are performed: `printf("%d ", array[exit(1),0]);` will not print anything :) – chqrlie May 11 '19 at 22:35
  • This is a important point @chqrlie . Thanks for adding this point. – Niloy Rashid May 11 '19 at 22:47