Skip to main content
gamedev.net
🔒 Locked

Proper statement?

Started by Endar 2 replies 400+ views
Original Post
Endar
Endar
Okay, in C++, how is this a proper statement?

(localX, localY, localZ, p1);
All of the vars are my own 3d vector class. So, how is this a proper syntactically correct statement? And, yes, I have checked the line above, and this is not a continuation of another line. Although, I stepped through with the debugger (VC++ 6), and it seems that the compiler optimizes it out, because the line is just skipped.
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
SiCrane
SiCrane
It's an expression followed by a semi-colon, which is a statement. The expression is a parenthetized comma expression. A comma expression evaluates each of the sub-expressions in turn and returns the value of the last expression. So basically, it evaluates localX, localY, localZ and p1 in turn and then has the value of p1, which is then discarded because the parenthized expression is not used as a value.
doynax
doynax
The comma operator simply executes the left hand side and returns the right.
So "x = 1, 2" will assign 2 to x for instance. And unlike the ternary operator they don't have to share types, the first part can even be a void expression.

I often use the following (somewhat unconventional) idiom based on the comma operator to get rid of compiler warnings:
if(ptr = CreateSomething(), ptr) { // success}
iMalc
iMalc
I see the comma operator most often used in for loops:
for (int i=0, j=10; i<10; i++, j--)
I've also seen it used as a means of avoiding using { ... }:
if (a > b) a-=b, b-=c, c-=d;
same as:
if (a > b) { a-=b; b-=c; c-=d; }

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.