Next: , Previous: Extensions to C, Up: Extensions to C


2.1.2.1 Blocks and conditional as expressions

In L, blocks can return a value. For instance:

     let Int a = { let Int sum = 0;
                   let Int i = 0;
                   for(i = 0; i <= 10; i++) { sum += i; }
                   sum };

The above code creates a new block where sum and i are two variables created in the block. An iteration is done, and then the value of sum is returned, and affected to a.

Note the syntax : if a block is supposed to return a value, it is composed of a list of statements followed by one expression. By contrast, the block in the for does not return a value, and is composed only of statements. This will be detailed more in Extending the syntax.

This will be very useful when you write Macros; but it is also good programming style : it is better to pass values around using this mechanism than creating a new variable to do it.

Conditionals can also return a value. Here is how to compute the absolute value of a :

     let Int abs_x = if(x >= 0) x else -x;

This eliminates the need for a distinct ? ... : operator.

Note: You can still use conditional as you would in C. The above example could also be written:

     let Int abs_x;
     if(x >= 0)
        abs_x = x;
     else
        abs_x = -x;

or even:

     let Int abs_x = x;
     if(x < 0)
       abs_x = -x;