0

While I was looking at the library code, I found the below line

int number = config.nodes,i,fanout=numP/2;

I assume config is a pointer to something, but can there be commas in the statement? and make assignment like that?

user482594
  • 16,878
  • 21
  • 72
  • 108

5 Answers5

8

This declares three variables. It's the same as:

int number = config.nodes
int i;
int fanout = numP/2;

Please note that commas are handled specially in declarations (and argument lists), C++ also has a "comma operator" which is not being used here.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 2
    It's also easy to confuse with the comma operator, so I wouldn't recommend doing it. I, personally, only do an initial assignment with the last declaration of a statement. – bdonlan Jul 11 '11 at 19:48
  • @bdonlan: Funny how I had an idea that mentioning the comma operator (by way of contrast) might be helpful. – Ben Voigt Jul 11 '11 at 19:50
  • 1
    I, personally, only do a single declaration in each statement. Saves people coming here and ask "WTF?". :-) – Bo Persson Jul 11 '11 at 20:07
1

It's valid, number is not being assigned the entire line you see though.

i and fanout are 2 other integers also being created at that time, fanout is also being initialized at this time.

That one line is equivalent to:

int number = config.nodes;
int i;
int fanout = numP/2;
Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
1

Its basically many declaration:

    int number = config.nodes;
    int i;
    int fanout=numP/2;
ghimireniraj
  • 397
  • 1
  • 5
0

A more recognizable way to write this would be:

int number, i, fanout;
number = config.nodes;
fanout = numP/2;

I personally would never write something like your example because it takes too long for the reader to work out what's going on.

Michael Kohne
  • 11,888
  • 3
  • 47
  • 79
  • 3
    For plain `int` it doesn't matter much, but your variation uses assignment instead of initialization. – Ben Voigt Jul 11 '11 at 19:51
0

I have the following additions:

1) The whitespace is always ignored by the C++ compiler. So,

int number  =   config.nodes,i,fanout=numP/2;

is equivalent to

// declaring three variables number, i and fanout
int number=config.nodes, i, fanout = numP/2; 

The comma here is to tell the compiler that i have more than one variable to declare. So, number will be initialized with config.nodes. If config is a pointer (as you mentioned above), then you cannot access member variables using . operator. You have to use -> instead of ..

2) The following line has different semantic:

// only one variable will be declared, which is number
int number  =  (config.nodes,i,fanout=numP/2);

Inside the parenthesis is an expression and the comma here is a comma operator. In this case, config, i, fanout and numP are previously defined. The value of comma operator is the value of last expression fanout=numP/2.

Eto700
  • 91
  • 3