C++Guns – RoboBlog

15.07.2018

C++ Guns: Why C++ don't need Python PEP 572 Assignment Expressions

Filed under: Allgemein — Tags: — Thomas @ 09:07

It is often a failure to assign a variable inside a if() instead to compare it. One can easily mistype '==' to '='. Both times the result can be converter to bool. To prevent this kind of error one languages simply forbid assignments inside if(), others have or introduce new operators.

But this is all unnecessary. Just make the variable 'const' so it's value can not change after the first assignment. No need for new operators or heavy discussions. But as far as I know there is no keyword 'const' to make the value immutable in python and the new language julia.
In C++ it is always possible to make a variable 'const'. The compile decides to reuse the memory the variable occupied. You don't have to do this by your own.

Example:

const auto x = func();
if(x = 5) {}

error: assignment of read-only variable 'x'

Advanced: Memory reuse for POD types

This is a simple,silly example how the compiler decide to reuse memory of one variable when it is no longer needed. Consider this code:

extern int func();
extern int func2();
auto example() {
    const auto x = func();
    int result =  x;    

    const auto y = func2(); // Memory of x is reused by y
    result = result + y;

    return result;
}

The two function 'func' and 'func2' are marked as 'extern' so they can't optimized away. The memory of variable x is reused by variable y, because x is no longer needed. The compiler can decide this without any hint from the user. There is no need to explicit define a scope or lifetime of variable x.
Let's introspect the generated assembler code:

example():
        call    func()      # call func store return value in x
        movl    %eax, %ebx  # copy x to result
        call    func2()     # call func2 store return value in y
        addl    %ebx, %eax  # add result to y
        ret                 # return y 

The result of a call to 'func' in line 1 is stored in register eax. This is the variable x. And the result of a call to 'func2' in line 3 is stored in register eax too. This is variable y now. The variable 'result' is stored in register ebx. No more memory is in use.

We have three variables but only two register in use. This is because I wrote a pretty silly example. You may also notice that in the C++ code the variable 'result' is returned. But in assembler the variable 'y' is returned. But the semantic is the same.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress