Weird casting in C++

What is the value of foo variable after execution of below line if foo is type of int?

foo = static_cast<int>(foo + 0.5);

At first it seems that this code doesn't do anything. Integer value is added to 0.5 but this 0.5 is removed when the value is cast back to integer.

Interesting here, is what happens, when foo is smaller that zero, then the result will be value of foo increased by one. Below is more detailed example and its output.

#include <iostream>

int main() {
    int foo;

    foo = 10;
    foo = static_cast<int>(foo + 0.5);
    std::cout << foo << std::endl;

    foo = -10;
    foo = static_cast<int>(foo + 0.5);
    std::cout << foo << std::endl;
}

bash-3.2$ ./a.out 
10
-9
This construction could be written as:
foo = 10;
if (foo < 0) {
    foo++;
}
std::cout << foo << std::endl;

0 commentaires:

Post a Comment