Skip to content

Instantly share code, notes, and snippets.

@avdi
Created November 28, 2011 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avdi/1401793 to your computer and use it in GitHub Desktop.
Save avdi/1401793 to your computer and use it in GitHub Desktop.
Function return as lvalue in C++
#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
@clifton
Copy link

clifton commented Nov 28, 2011

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