Java allows assignments inside expressions, but not variable declarations (thanks for the correction biziclop!). C++ has traditionally had the same restriction, but I found another stackoverflow post describing how declarations are allowed in conditions in the C++03 standard. The syntax is limited, but this is allowed (tested on GCC 4.2.1):
int x = 1;
if (int y = x)
cout << "y = " << y << endl;
Note that as biziclop pointed out, this has the nice property of restricting the scope of y
to that within the conditional. If you try to use y
outside the conditional you'll get an error:
int x = 1;
if (int y = x)
cout << "y = " << y << endl;
cout << y; // error: ‘y’ was not declared in this scope
I don't think there's actually a name for this—it's just allowing declarations in expressions. I don't think it's common enough to have its own specialized term.
As for language support. JavaScript sort of supports this in that it allows assignments in expressions, and that if you reference an undeclared variable in JavaScript it just assumes it's global.
if (x = 1) alert(x) // x is global, assigned 1
alert(x) // since x is global it's still in scope and has value 1
Basically, any language in which a declaration is an expression will allow you to do this. In most functional programming languages (e.g. Haskell, ML, Lisp), basically everything is an expression, so you can declare new variable bindings inside the condition (but they wouldn't be available in the body of the conditional). Here's an example in Clojure:
(println ; print the result of the conditional
(if (let [x 1] ; declare local binding x = 1
(== x 2)) ; check if x == 2
"is two" ; true branch result
"isn't two")) ; false branch result