3

Possible Duplicate:
C++ Comma Operator

About a year ago I noted some obscure syntax in a coding project I was working on:

table_value = table_index += 2, valueFromTable(table_index);

Does anyone recognise this?, it's like an assignment with an additional statement. This compiled in our entire suite of cross-platform compilers, so I'm pretty certain its valid C++ but I've never seen anything like it.

Any insight would be appreciated.

Gearoid

EDIT: heres some working code:

#include <iostream>
using namespace std ;

int valueFromTable(int a) { return a ; }

int main()
{
  int table_index = 0 ;
  int table_value = table_index += 2, valueFromTable(12);
  cout<<table_value<<endl;
  return 0 ;
}
Community
  • 1
  • 1
Gearoid Murphy
  • 11,834
  • 17
  • 68
  • 86

1 Answers1

6

This is the Comma operator.
It's standard C and C++ but heavily frowned upon.

It evaluates both arguments, and returns the result of the second.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Is this the same when used in `for` loops? `for (size_t i = 0; i < limit; ++i, ++some_other)` Just a qualification on the 'heavily frowned upon' part if so, ie. avoid when it's obfuscatory. – Steve Townsend Nov 07 '10 at 14:26
  • 3
    @Steve: "heavily frowned upon" doesn't mean "always a bad idea", it just means someone always thinks it's a bad idea. I call this the "passive-aggressive voice": "oh no, it's not *me* criticising *your* code. It's just that people don't like it, in general, when it happens". The kind of generalization that on Wikipedia attracts those little [Who?] tags ;-) – Steve Jessop Nov 07 '10 at 14:30