Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Similar syntax but one shows error but another does not

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

like image 915
shrutisingh Avatar asked Aug 14 '10 16:08

shrutisingh


2 Answers

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

like image 141
Prasoon Saurav Avatar answered Oct 14 '22 07:10

Prasoon Saurav


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.

like image 34
Heath Hunnicutt Avatar answered Oct 14 '22 07:10

Heath Hunnicutt