views:

64

answers:

5

Hiii all

I made this program today

int main()
{
   int a = 1,2; /* Shows error */
   int b = (1,2); /* No error */
}

Why first one shows error while second one does not? Just ( ) makes one program compile. Why?

--Shruti

A: 

(1,2) evaluates to the last expression in the list, i.e. 2.

Another example: (a,b,c) would evaluate to c.

In case you want to use a fractional number, use a float/double type and use the dot as a decimal symbol: double d = 1.2;

ThiefMaster
+5  A: 

Inside the parentheses, the language specifies an expression will occur. In that case (b), the comma represents the comma operator from C.

Without parentheses, the language specifies that variable declarations are separated by commas. In the example of a, the compiler (parser) is expecting additional variable declarations.

Heath Hunnicutt
+10  A: 

int a = 1,2; 2 is treated as a variable name which cannot start with a number, hence the error.

int b = (1,2); comma operator evaluates the operands from left to right and returns the last expression in the list i.e. 2

Prasoon Saurav
+2  A: 

The reason is in your first statement int a = 1,2; the comma is not parsed to be a sequence operator. It is part of a declaration list and attempts to instantiate an integer variable named 2 which is not allowed by the language.

The parentheses in the second statement int b = (1,2); force the comma to be parsed as a sequence operator.

Amardeep
A: 

None of them made sense to me at fist.

But then i remembered multiple operations in for loops. Eg:

for (a=1,b=2; a<1; a++)

Knowing that 1 is a valid expression, and that expressions are valid language elemnts, my conclusion is that (1,2) evaluates 1 (but does nothing with it), then evaluates 2 and returns 2.

And finally:

b = (1,2);

What does is evaluate 1 and 2 as before, return 2, and assign it to b.

LatinSuD