Forgotten C: The comma operator
mindtribe.com
mindtribe.com
http://stackoverflow.com/questions/52550/what-does-the-opera...
string s;
while(read_string(s), s.len() > 5)
{
//do something
}
versus string s;
read_string(s);
while(s.len() > 5)
{
//do something
read_string(s);
} for (read_string(s); s.len() > 5; read_string())
or just fix the damned read_string function to return the length read. [nevermind s.len() is unlikely to appear in C.]I'd say the for version is better if you can declare the variable in the initialization section (tighter scope), but the while version has you repeat yourself less if the variable's already there.
string s;
for (;;)
{
read_string(s);
if (s.len() <= 5)
break;
//do something
} if (...)
{
cleanup();
return -2;
}
to this if (...)
return cleanup(), -2;
Linux kernel uses this pattern in several places. However the best comma use is, of course, for messing your enemies' code: foo,(); #define something(...) (printf(... some debug message ...),real_something_expression)
foo = something(...)
This way you can create macros returning values and printing debug messages at the same time. MyType obj = 1, 2, 3;
Due to the precedence of operators, this is actually equivalent to ((MyType obj = 1), 2), 3;
so as long as the overloaded assignment operator returns an object that the comma operator mutates and returns, this can be made the have effect of initializing the declared object to a "list".This trick is used by Boost Spirit to allow things like (example from http://stackoverflow.com/questions/54142/c-comma-operator)
keywords = "and", "or", "not", "xor";It's special in the fact that it's written by Hanson (who also co-wrote the LCC compiler, you might have seen ID Software use this compiler) and the book uses Knuth's Literary Programming technique for the source code in the book ;)
for (i = 0, j = strlen(s)-1; i < j; i++, j--)
c = s[i], s[i] = s[j], s[j] = c; if (something) f();
else delete x, x = NULL;
Of course, I don't personally use "else" without a block, so it's just an example; I'm not suggesting it's a good idea. my ($a) = (8,9) || (20,21);
print "\$a = $a\n";
Gives: $a = 9
Due to the comma operator. while (read_string(s) > 5) // loop until the string length is greater than 5
because it's not intuitive that read_string will return the length of the string. You don't save anything this way.while (strlen(read_string(s)) > 5)
(++k, ++k, k) += 100;
(works with gcc 3.4)