Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22165

Variable declaration as side-effect

$
0
0

So I'm looking over C++ operator rules as I do when my programs start behaving wonkily. And I come across the comma operator. Now, I have known it was there for a while but never used it, so I began reading, and I come across this little gem:

if (int y = f(x), y > x){    // statements that use y}

I had never thought about using commas' first arguments' side-effects to get locally-scoped variables without the need for bulky block-delimited code or repeated function calls. Naturally, this all excited me greatly, and I immediately ran off to try it.

test_comma.cpp: In function 'int main()':test_comma.cpp:9:18: error: expected ')' before ',' token  if (int y = f(x), y > x) {

I tried this on both a C and C++ compiler, and neither of them liked it. I tried instead declaring y in the outer scope, and it compiled and ran just fine without the int in the if condition, but that defeats the purpose of the comma here. Is this just a GCC implementation quirk? The opinion of the Internet seems to be that this should be perfectly valid C (and ostensibly, to my eye, C++) code; there is no mention of this error on any GCC or C++ forum that I've seen.


EDIT: Some more information. I am using MinGW GCC 4.8.1-4 on Windows 7 64-bit (though obviously my binaries are 32-bit; I need to install mingw-w64 one of these days).

I also tried using this trick outside of a conditional statement, as below:

int y = (int z = 5, z);

This threw up two different errors:

test_comma.cpp: In function 'int main()':test_comma.cpp:9:11: error: expected primary-expression before 'int'      int y = (int z = 5, z);       ^test_comma.cpp:9:11: error: expected ')' before 'int'

With creative use of parentheses in my if statement above, I managed to get the same errors there, too.


Viewing all articles
Browse latest Browse all 22165

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>