Programming by Optimisation (PbO)

[What is PbO?] · [PbO Levels] · [Literature] · [Examples] · [Tools] · [Best Practices] · [FAQ]


Best Practices

Choices over variable declarations

In programming languages such as C and C++, certain choices over variable declarations can lead to undesirable differences in semantics between parametric and instantiation mode when weaving.

Consider the following example:

    int x=2;
    
    int main() {
    	##BEGIN CHOICE diffX
    		int x=3;
    	##END CHOICE diffX
    	
    	printf("x is %d", x);
    }
    

Because of the specific way in which the C and C++ weavers resolve this choice in parametric mode, x will take the value 2 if diffx is selected, since the code fragment inside the choice will be treated as a separate block of code. However, when instantiating the same choice in the weaver, no block is created, so that x will take the value 3.

To avoid this issue, we recommend that choices involving variable declarations always be specified in the form of complete blocks, as in the follwing:

    int x=2;
    
    int main() {
    	##BEGIN CHOICE diffX
    		{
		int x=3;
		}
    	##END CHOICE diffX
    	
    	printf("x is %d", x);
    }
    

We further note that proper use of PbO needs to ensure that all choice instances are semantically equivalent - something that is clearly violated in the example above. For pragmatic reasons, PbO language extensions and weavers do not enforce this constraint, but beware that unintuitive (and outright weird) behaviour may result from breaking it. You have been warned!