The Secret Expression Language Inside C++
An expression language is a language where every executable statement produces a value. The vestigal expression language embedded in C++ includes individual expressions, sequences, blocks, if/else, and function call, but not iteration, alas.
x = 1, y = 2, z = x + y
is a sequence. It sets the values of variables x, y, and z, and produces the value 3.(rand(), 0)
is a block. It calls the function rand()
, and produces the value 0.
x == 1 ? y : (z, 0)
is an if/else statement. It evaluates the boolean condition x == 1
. If x and y have the values set in the previous expression, it produces the value 2. If x is not equal to 1, it produces zero.
C++ Has a Shiny New Functional Language Too
Here's the old syntax for a function.
int foo(int x)
{
return x*x-1;
}
Here's the same function as a lambda. Return value in a different place. Syntax for associating a name with the function different. New rules to remember about the difference between lambdas and function pointers.
auto foo = [](int x)
{
return x*x-1;
};
Lambdas have a whole new scheme (ouch, pun) of type deduction rules. Someday they are going to be special. But today they are mostly syntactic sugar, for people who grew up with Javascript or some exotic functional language so they can pretend that C++ is trendy too.