Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "int i=1,2,3" and "int i=(1,2,3)" - variable declaration with comma operator [duplicate]

Tags:

c

  1. int i=1,2,3;

  2. int i=(1,2,3);

  3. int i; i=1,2,3;

What is the difference between these statements? I can't get to any particular reason for it.

like image 299
Robert Roman Avatar asked Dec 05 '22 10:12

Robert Roman


1 Answers

Statement 1 Result : Compile error.

'=' operator has higher precedence than ',' operator. comma act as a separator here. the compiler creates an integer variable 'i' and initializes it with '1'. The compiler fails to create integer variable '2' as '2' is not a valid indentifer.


Statement 2 Result: i=3

'()' operator has higher precedence than '='. So , firstly, bracket operator is evaluated. '()' operator is operated from left to right. but it is always the result of last that gets assigned.


Statement 3: Result: i=1

'=' operator has higher precedence than ',' operator. so 'i' gets initialized by '1'. '2' and '3' are just constant expression. so have no effect .

like image 141
S J Avatar answered Jun 03 '23 00:06

S J