Thursday, June 25, 2015

The Mysterious Hidden Languages of C++

C++ is old enough to have teenaged children (like Java, conceived when C++ was itself a wild teenager). Some lucky developers have spent virtually their whole career writing C++. But while C++ grew and solidified, the world of programming languages bubbled and foamed around it. Languages and language ideas came and went. Lexical styles changed and changed again. In these modern days of Hascell, python and Javascript, it can be hard to remember that the folks who originally designed C and C++ learned to program in BCPL.
 

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.

No comments:

Post a Comment