Search code examples
c++c++11clangclang-extensions

c++ constant type conversion in arithmetics


Background

I am trying to learn in C++11 with clang on mac.

Question

As it is said in the book, when float type meets int or lower case in arithmetic, the latter will be converted to float. It is true in cases like:

cout << 9.0 / 5 << endl;

The result yields 1.8000, but when I try to use suffix to ensure the type for the constants like:

cout << 9.0f / 5i << endl;

The result yields 1. I wonder why? Are there different rules or mechanism behind it?


Solution

  • Using i as a suffix is an extension which indicates an imaginary constant as opposed to an integer that is also supported by gcc. Without warnings enables clang will just interpret 5i as a complex number. With warning turned on(specifically -Wconversion) it gives the following warning:

    warning: imaginary constants are a GNU extension [-Wgnu-imaginary-constant]
    std::cout << 9.0f / 5i << std::endl;
                        ^
    
    warning: implicit conversion discards imaginary component: '_Complex float' to 'bool' [-Wconversion]
    std::cout << 9.0f / 5i << std::endl;
    ~~~          ~~~~~^~~~
    

    So it looks like there is no overload for _Complex so the result is being converted to bool. We can see this more clearly using the following examples:

    float f = (9.0f / 5 + 0i) ;
    std::cout << f << std::endl ;
    

    which outputs 1.8.

    If you just want an int literal then no suffix is needed, the other integral suffixes are u, l, ul, ll, ull for unsigned, long, unsigned long, long long and unsigned long long respectively.

    So in your case:

    9.0f / 5
    

    would be what you want if you want to insure 9.0 is interpreted as a float otherwise it will be interpreted as a double.

    5 will be converted to a float as well since the / operator will perform the usual arithmetic conversions on it's operands.