Search code examples
cgccvariable-assignmentcomma-operator

a=3,2,1; gives error in gcc


I tried the following code in gcc:

#include<stdio.h>
int main()
{
    int a=3,2,1;//////////////////////ERROR!//////////////////////////
    printf("%d", a);
    return 0;
}

I expected it to compile successfully as:

  • a series of integer expressions seperated by commas will be evaluated from left to right and the value of the right-most expression becomes the value of the total comma separated expression.

Then, the value of the integer variable a should have been 1 right? Or is it 3?

And why am I getting this error when I try to execute this program?

error: expected identifier or '(' before numeric constant


Solution

  • If you separate the initialization from the declaration, you may get what you expected:

    int a;
    a = 3, 2, 1;     // a == 3, see note bellow
    

    or

    int a;
    a = (3, 2, 1);   // a == 1, the rightmost operand of 3, 2, 1
    

    as your original command is syntactically incorrect (it is the declaration so it expected other variables to declare instead of numbers 2 and 1)

    Note: All side effects from the evaluation of the left-operand are completed before beginning the evaluation of the right operand.

    So

    a = 3, 2, 1
    

    which are 3 comma operators a = 3, 2 and 1 are evaluated from left to right, so the first evaluation is

    a = 3, 2
    

    which result 2 (right-operand) (which is by the way not assigned to any variable, as the value of the left-operand a = 3 is simply 3), but before giving this result it is completed the side effect a = 3 of the left-operand, i. e. assigning 3 to variable a. (Thank AnT for his observation.)