3

The second dimension of the array is not clear. The size of this array is 48, where int is 2 bytes but what is the exact difference between int a[6][4] and int a[6][(2,2)]?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Shifa Agrawal
  • 67
  • 1
  • 1
  • 2
  • 6
    Just another case of meaningless, obfuscated code. I have no idea why people are so fascinated with such nonsense and wildly up-vote any topic regarding it... [What does the comma operator do in C?](http://stackoverflow.com/questions/52550/what-does-the-comma-operator-do-in-c). โ€“ Lundin Apr 01 '15 at 07:01

3 Answers3

14

what is the exact difference in int a[6][4] and int a[6][(2,2)]?

There is a big difference. int a[6][(2,2)] is largely equivalent to int a[6][2]. The (2,2) expression involves the comma operator and evaluates to 2.

The subtle difference (see comment from @Virgile) is that (2,2) is not a constant expression in C. So int a[6][(2,2)] is really a size 6 array of size 2 variable length arrays. So technically, it really is equivalent to

int n = 2;
int a[6][n];
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    Actually, `int a[6][(2,2)]` is not _exactly_ the same as `int a[6][2]`: `(2,2)` is not an integer constant expression (in the sense of section 6.6 of the standard). This means that the former is technically a variable length array which cannot be used everywhere. For instance `gcc` will reject such declaration as a global variable. โ€“ Virgile Apr 01 '15 at 08:21
  • @Virgile That's interesting. It seems to be a constant expression in C++. I clarified this. โ€“ juanchopanza Apr 01 '15 at 09:12
3

In your code

int a[6][(2,2)]

is essentially

int a[6][2];

Description:

As per the C11 standard, chapter ยง6.5.17, the comma operator ,

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

int a[6][(2 , 2)];
          ^   ^
          |   |
         [A]  |
             [B]

Let's assume, A and B are the two operands of the , operator. Then, sequentially

  1. A is evaluated to 2 (as a void expression;). The result is discarded.
  2. B is evaluated to 2. As the result of , operator has right side operand's type and value, the final result is 2.

So essentially, int a[6][(2,2)]; becomes int a[6][2];

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1
int a[6][(2,2)] = int a[6][2];

comma(,) operator has a least percedence so you get a array as above.

You can test it out for yourself

int main(void) {
int a[6][4];
int b[6][(2,2)];

printf("%d\n",sizeof(int));
printf("%d %d\n",sizeof(a),sizeof(b));
    return 0;
}

int x = (3,4); so what do you expect the value of x to be?

It evaluates to x=4 the same applies to your array also.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
Gopi
  • 19,784
  • 4
  • 24
  • 36