vendredi 23 octobre 2020

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 do not want this can be compiled with no warning
    // I want only x=(double)i, or x=std::static_cast<double>i, that can compiled with no 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 show warning unless I explicitly told the compiler it should be 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.

Aucun commentaire:

Enregistrer un commentaire