Created
November 28, 2011 20:01
-
-
Save avdi/1401793 to your computer and use it in GitHub Desktop.
Function return as lvalue in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
int& foo() { | |
static int pointless_static_var = 23; | |
return pointless_static_var; | |
} | |
int main(int argc, char** argv) { | |
std::cout << "foo() = 42: " << (foo() = 42) << std::endl; | |
} | |
// Outputs: | |
// foo() = 42: 42 |
Yeah, it's particularly important with the threequals (`===`) since
that operator is rarely symmetric.
"constants on the left-hand side when performing equality comparisons"
Some people call those "Yoda-assignations", for obvious reasons.
My only complains are: 1) They don't look very nice and 2) You don't always have a constant to compare - you could do foo() = bar()
. Help you Yoda will not on that one.
Yoda. I love it!
A similar argument is applicable in JavaScript-land, where I see many (particularly nodejs) programmers use comma-first variable declaration.
var ruby = "is pretty cool"
, yoda = "not so pretty think yoda does"
This type of notation will trigger syntax errors when you make a mistake, which is preferable to creating globals accidentally.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've always disliked how that looks, but I can't deny the logic of it.
Actually, it can be important to follow this general pattern in other languages too. Another classic example in ruby, of doing equality comparisons, is that the equality 'operator', being just a method dispatch, you want to execute on developer supplied data not user supplied data, as that's more deterministic. In short, exactly as above, put your 'constants' (even if that's just your "baseline object") on the left hand side to increase the likelihood of deterministic and expected dispatching.