C++ implicit numeric type demoting -
recently, have noticed c/c++ seems permissible numeric type conversion, implicitly casts double int.
test:
environment: cpp.sh, standard c++ 14, compilation warnings set
code:
int intforcingfunc(double d) { return d; // allowed } int main() { double d = 3.1415; double result = intforcingfunc(d); printf("intforcingfunc result = %f\n", result); int localres = d; // allowed printf("local result = %d\n", localres); int staticcastres = static_cast<int>(d); // allowed printf("static cast result = %d\n", staticcastres); } no warnings issues during compilation.
documentation mentions tangentially subject, misses exact case of question:
c++ strong-typed language. many conversions, specially imply different interpretation of value, require explicit conversion, known in c++ type-casting.
i have tried in managed language (c#) , these cases not allowed (as expected):
static int intforcingfunc(double d) { // not legal: cannot implicitly convert type 'double' 'int' // return d; return convert.toint32(d); } static void main(string[] args) { double d = 3.1415; double result = intforcingfunc(d); console.writeline("intforcingfunc result = " + result); // not legal: cannot implicitly convert type 'double' 'int' // int localres = d; int localres = (int)d; console.writeline("local result = " + result); console.readline(); } why behavior allowed in strong-typed language? in cases, undesired behavior. 1 reason behind seems lack of arithmetic overflow detection.
unfortunately, behavior inherited c, notoriously "trusts programmer" in these things.
the exact warning flag implicit floating-point integer conversions -wfloat-conversion, enabled -wconversion. unknown reason, -wall, -wextra, , -pedantic (which cpp.sh provides) don't include these flags.
if use clang, can give -weverything enable literally warnings. if use gcc, must explicitly enable -wfloat-conversion or -wconversion warning when doing such conversions (among other useful flags want enable).
if want, can turn error e.g. -werror-conversion.
c++11 introduced whole new safer initialization syntax, known uniform initialization, can use warnings implicit conversions in example without enabling compiler warnings:
int intforcingfunc(double d) { return {d}; // warning: narrowing conversion of 'd' 'double' 'int' inside { } } int main() { double d{3.1415}; // allowed int localres{d}; // warning: narrowing conversion of 'd' 'double' 'int' inside { } }
Comments
Post a Comment