Home > Net >  Is using the value of assignement just obfuscating or is there any performance benefits?
Is using the value of assignement just obfuscating or is there any performance benefits?

Time:09-30

For example, is there any difference between :

void f(int a, int& b){
    b = a%2;
    if (b!= 0) {
        //do something;
    }
    //do some other things;
}

and

void f(int a, int& b){
    if ((b = a%2)) {
        //do something;
    }
    //do some other things;
}

beyond readability and aesthetics?

My assumptions is that the second one might save a couple cycles but might be considered bad practice, and the first one might be equivalent with a smart enough compiler, but I have no idea really.

CodePudding user response:

The performance will be identical.

beyond readability and aesthetics?

Ignoring performance, then assignment inside expressions is considered dangerous style for a number of other reasons. There is the potential of mix-ups with equality operators and it is making control expressions needlessly brittle by including a side effect inside them.

This is not just a style matter, it's a matter of writing needlessly dangerous code on purpose. Most compilers will warn for assignment inside control expressions. The extra parenthesis trick to silence warnings for certain compilers, is not something I would recommend to make a habit of using either. Only use assignment inside control expressions as a last resort.

CodePudding user response:

There's not much point to it in an if statement. But similar style is often used with while:

while (data = somefunction()) {
    // code
}

Splitting this up into separate statements would require something like:

while (true) {
    data = somefunction();
    if (!data) {
        break;
    }
    // code
}

or

data = somefunction() {
while (data) {
    // code
    data = somefunction();
}

The first rewrite is significantly more verbose (1 line has become 5), the second requires multiple data = somefunction() calls. So the terse version has become idiomatic, and isn't considered obfuscating.

  •  Tags:  
  • c
  • Related