Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why different behavior in two cases 1st. int i = 1,2,3; and 2nd. int i; i = 1,2,3; [duplicate]

Tags:

c++

c

operators

Working on GCC compiler, with following two cases of operators in C program, observed different behaviors.

1.

 int i = 1,2,3;

 printf("%d",i);                     // this will give compile time error

And,

2.

int i;

i = 1,2,3;

printf("%d",i);    // Its output will be 1.

In 1st case compiler gave error "error: expected identifier or ‘(’ before numeric constant". And in second case, no errors, and output is 1. Can anybody explain here the compiler behavior in both the cases in detail? How does compiler interpret both statements?

Thanks in advance for your inputs.

like image 470
Arti Avatar asked Nov 23 '13 14:11

Arti


1 Answers

  1. In the first case the comma separates declaration and initialisation of several variables of the same type:

    int i = 1, j = 2, k = 3;
    

    You can add parentheses to tell the compiler it's an expression.

    int i = (1, 2, 3);
    

    If you combine them, it's easier to see why the comma is ambiguous without parentheses:

    int i = (1, 2, 3), j = 4, k = 5;
    
  2. In the second case the comma separates 3 expressions.

    (i = 1), 2, 3
    
like image 122
Alex B Avatar answered Sep 21 '22 17:09

Alex B