开发者

Is this a valid assignment in C++?

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, 开发者_StackOverflow中文版but can there be commas in the statement? and make assignment like that?


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.


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;


Its basically many declaration:

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜