Home > Mobile >  Why does using parenthesis make a multi dimentional array behave like this?
Why does using parenthesis make a multi dimentional array behave like this?

Time:12-05

I accidentally covered the numbers with these instead of the curly brackets normally used and got "2 4 0 0". Why does this shifting happen?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
    int a[2][2]={(1,2),(3,4)};
    for (int i = 0; i < 2;   i)
    {
        /* code */
        for (int j = 0; j < 2;   j)
        {
            /* code */
            printf("%d ",a[i][j] );
        }
    }
    return 0;
}

CodePudding user response:

In the braces of the list initialization in this declaration

int a[2][2]={(1,2),(3,4)};

there are present two expressions ( 1, 2 ) and ( 3, 4 ). They are primary expressions with the comma operator.

According to the C Standard (6.5.17 Comma operator)

2 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

So the values of the expressions are 2 and 4.

Thus in fact you have

int a[2][2]={ 2, 4 };

As a result the first sub-array of the array that is the array a[0] is initialized with these values. Elements of the second sub array a[1] are zero initialized.

If for example you would write

int a[2][2]={(1,2,3,4)};

then this declaration is equivalent to

int a[2][2]={ 4 };

and only the element a[0][0] will be explicitly initialized by the value 4,

Another example of using an expression with the comma operator as an initializer.

int i = 0;
int j = ( i  , i  , i   );

As a result i will be equal to 3 and j to 2.

CodePudding user response:

You accidentally used the comma operator. In your case it did nothing, but the resulting value from it is the last value in the comma separated list: (1,2) results in the last value 2 and (3,4) results in 4.

So your code was equivalent to:

int a[2][2]={2,4};

The last two of the four values in a were not provided, so they were initialized implicitly with zeroes. This post explains exactly why.

  • Related