c++c++11narrowing

How do I forbid an implicit conversion from int to double in C and C++?


There is a simple a program:

#include <iostream>
int main()
{
    int i = 1;
    double x = 2.5;
    x = i; // I don't want this to compile without warning.
    // I only want x=(double)i, or x=std::static_cast<double>(i) to compile without warning.
    std::cout << "x = " << x << std::endl;
    return 0;
}

I do not want implicit conversion from int to double in my program.

I want the compiler to display warnings unless I explicitly tell it that it is a conversion.

I compiled the program with GNU compiler g++ or intel C++ compiler icpc, there is no warning.

g++ main.cpp -Wall
icpc main.cpp -Wall

Is there something I can configure to implement the strict type conversion checking?

I am working in C++11, the C solution is also appreciated.

Thanks for your time.


Solution

  • I believe you are looking for these warning flags:

    -Wconversion -Warith-conversion

    -Warith-conversion
    
        Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from -Wconversion, -Wfloat-conversion, and -Wsign-conversion.
    
        void f (char c, int i)
        {
          c = c + i; // warns with -Wconversion
          c = c + 1; // only warns with -Warith-conversion
        }
    
    

    https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options

    EDIT:

    If this isn't enough for you then you might be running into a bit of a wall.

    But there are possible alternatives.

    https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-narrowing

    There is a coreguideline that covers narrowing conversion issues.

    While coreguidelines aren't generally covered by compilers other static analyzer tools might be up your alley.

    Clang-tidy: https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-narrowing-conversions.html

    Cpp-core-check: https://devblogs.microsoft.com/cppblog/c-core-check-in-visual-studio/

    If none of these are the solution then what you are looking it as completely legal conversions that are specified by C++. Because everything I'm describing/linking is to narrowing conversions. If your code won't cause a narrowing conversion then I don't believe any tool will currently catch this (as far as I know). Because it is completely legal C++.