0

I made some code that looks like this:

int foo, bar1 = 4, bar2 = 7;

foo = bar1, bar2; // Look at this expression.

printf("%d", foo);

Compiled it with GCC, with -Wall and -Wextra. The output was 4.

Apart from being ugly, is this expression undefined behaviour, or is foo always set to bar1?

pampeho
  • 704
  • 6
  • 12
  • It should be outputting 74. http://en.wikipedia.org/wiki/Comma_operator "In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type)." but assignment is a higher precedence, so it assigns first then discards. – Paul Tomblin Aug 29 '13 at 17:34
  • 3
    @PaulTomblin True, but I think `,` has lower precedence than `=`. – C. K. Young Aug 29 '13 at 17:35
  • @PaulTomblin Its also at the bottom of the precedence chart (last I checked) so in the OP's question the assignment operator is taking precedence first, and the eval of `bar2` is essentially worthless. – WhozCraig Aug 29 '13 at 17:35
  • Ah, right you are, @ChrisJester-Young – Paul Tomblin Aug 29 '13 at 17:36
  • putting `foo = (bar1, bar2);` instead makes it output `7`, but gives a warning. – pampeho Aug 29 '13 at 17:36
  • @Zupoman with parens that should yield `bar2`'s value into `foo`. And the warning should essentially be that `bar1`s value is unused in the expression (or something similar). – WhozCraig Aug 29 '13 at 17:37

3 Answers3

1

It is the comma operator, mostly useful with side-effecting expressions like foo = (bar1++, f(bar2)); which increments bar1, call function f with bar2 and set its result to foo

In C the comma operator has lower precedence than assignment.

In general e1,e2 (in expression context) evaluates the left operand e1, discards its result, then evaluate the right operand e2 and gives the value of the right operand (as the value of the entire e1,e2 expression).

Ocaml has the ; operator, Scheme has begin, Lisp has progn for similar purposes (evaluating two or several sub-expressions for side effects, and giving the last as the entire result).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

In that expression you are using the , operator which evaluates it operands from left-to-right and returns the last. So it evaluates foo = bar1 and then bar2.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
0

here

foo = bar1;

for deeper understanding,

int foo = barx, * barp;

Here , operator means

int foo = barx;
int *barp;
sr01853
  • 6,043
  • 1
  • 19
  • 39