The difference between "int i = 1,2,3" and "int i = (1,2,3)" is a variable declaration with a comma

  • int i=1,2,3;

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

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

What is the difference between these statements? I can not understand the reason for this.

+4
c
source share
2 answers
 Statement 1 Result : Compile error. 
Operator

'=' has a higher priority than the operator ",". the comma acts as a delimiter. the compiler creates the integer variable "i" and initializes it with "1". The compiler cannot create the integer variable "2" because "2" is not a valid index.


 Statement 2 Result: i=3 
Operator

'() takes precedence over' = '. So, firstly, the parenthesis operator is computed. The '()' operator works from left to right. but it is always the result of the latter, which is assigned.


 Statement 3: Result: i=1 
Operator

'=' has a higher priority than the operator ",". therefore, 'i' is initialized to '1'. '2' and '3' are just a constant expression. therefore have no effect.

+13
source share

This is a comma operator.

 i = a, b, c; // stores a into i ... a=5, b=2, c=3, i=5 i = (a, b, c); // stores c into i ... a=5, b=2, c=3, i=3 

different behavior between the first and second lines is associated with the comma operator, which has a lower priority than the destination.

0
source share

All Articles