0

code snippet:

void main()  
{  
    int a=1,3,15;//why it is allowed, generating warning no error  
    int b=(1,2,4);//what it signifies writing value in ()  
printf("%d",a+b);  
}  

I want to know what is use specifying values in round braces???

melpomene
  • 84,125
  • 8
  • 85
  • 148
kashif k
  • 55
  • 1
  • 6
  • Look in your C book about the comma operator. It allows to write several expressions in sequence giving as result the value of the last one. It's perfectly legal. In a variable declaration, it's used by the syntax to separate several variable declarations, so the first one will give an error, as pointed in one of the answers. – Luis Colorado Sep 08 '15 at 19:12
  • first line gives warning as 'code has no effect' but not error – kashif k Sep 10 '15 at 05:32
  • sorry, but the declaration `int a=1, 3, 15;` generates an error, just before reading the `3`. `pru.c:14:15: error: expected identifier or ‘(’ before numeric constant` (gcc (Debian 4.6.3-14+rpi1) 4.6.3) – Luis Colorado Sep 11 '15 at 09:23

3 Answers3

1
int a=1,3,15;

is not allowed:

prog.c: In function ‘main’:
prog.c:2:13: error: expected identifier or ‘(’ before numeric constant
     int a=1,3,15;

This is because it is parsed as a list of declarations, the items being a=1, 3, and 15 (and 3 is not a valid variable name).

If you write

int a;
a = 1,3,15;

that is parsed as (a = 1), 3, 15; because = binds tighter than ,.

On the other hand,

int b=(1,2,4);

declares a single variable b initialized from the expression (1,2,4). The parens are simply for grouping.

, (comma) is an operator that evaluates (and throws away the result of) its left operand, then evaluates and returns its right operand. So b ends up being 4 (and some compilers will warn about ignoring the values of 1 and 2).

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

The parenthesis evaluate the expression. Consider:

int a = (2, 4);

This sets a equal to the result of the evaluating the expression 2, 4.

Your next question is probably what the comma operator does. It evaluates the first expression, throws the result away, evaluates the second expression, and then the expression evaluates to the type and value of that second expression. So the expression 2, 3evaluates to 3.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • See also (for an explanation as to why it might be useful): http://stackoverflow.com/questions/52550/what-does-the-comma-operator-do-in-c – druckermanly Sep 08 '15 at 07:42
0
int a=1,3,15;

is not valid, at least a diagnostic has to generated and the compiler to refuse to translate the code.

int b=(1,2,4);

is valid and equivalent to:

int b=4;

The comma expression (1, 2, 4) is equivalent to ((1, 2), 4) and evaluates to 4.

ouah
  • 142,963
  • 15
  • 272
  • 331