Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 762
J...S Avatar asked Oct 28 '16 16:10

J...S


2 Answers

That's parsed as a three-part variable declaration, with two invalid variables.

You need to wrap the entire initializer in parentheses so that it's parsed as a single expression:

int a=(3,2,1);
like image 121
SLaks Avatar answered Sep 26 '22 23:09

SLaks


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.)

like image 24
MarianD Avatar answered Sep 24 '22 23:09

MarianD