why this code can run ? double a[3]; a[1,1]=1;

后端 未结 3 1489
攒了一身酷
攒了一身酷 2021-01-29 04:38
int main()
{
    double a[3];  
    a[1,1]=1;
}

It passes the vs2013 compiler, and it is not 2D array.

相关标签:
3条回答
  • 2021-01-29 04:44

    In the expression inside square brackets there is so-called comma operator.

    a[1,1]=1;
    

    Its value is the value of the last subexpression.

    So this statement is equivalent to

    a[1]=1;
    

    This syntax as

    a[1,1]=1;
    

    is also valid in C# but it sets an element of a two-dimensional array.

    In C/C++ each index of a multidimensional array shall be enclosed in separate square brackets.

    Here is a more interesting example with the comma operator

    int main()
    {
        double a[3];  
        size_t i = 0;  
        a[i++, i++]=1;
    }
    

    It is also equivalent to

        a[1]=1;
    
    0 讨论(0)
  • 2021-01-29 05:00
    a[1,1]=1;
    

    is equivalent to:

    a[1]=1;
    

    The expression 1,1 evaluates to 1, because the first 1 is discarded and only the second 1 is evaluated. Read up on the comma operator for more info.

    0 讨论(0)
  • 2021-01-29 05:06

    You are invoking the comma operator. This evaluates its first operand, discards it, and returns the second one. So your code is the equivalent of

    a[1] = 1;
    

    The syntax for accessing an element of a 2D array would be

    b[1][2] = 42;
    
    0 讨论(0)
提交回复
热议问题