简体   繁体   中英

C++ Type Check in Functions ignored (required double, provided int)

I have the following code

#include <iostream>

using namespace std;

int dmult(int a, int b){
    return 2*a*b;
}

int main(void)
{
    double a = 3.3;
    double b = 2;
    int c = dmult(a,b);
    cout << c << endl;
    return 0;
}

It compiles with MinGW without problems. The result is (as I thought) false. Is it a problem of the compiler that there is no warning, that a function expecting integers, but fed with doubles, can compile without warning even if the input type is wrong? Does it mean that C++ ignores the input type of a function? Shouldn't it realize that the function arguments have the wrong type?

double 's are implicitly convertible to int s (and truncated), and the compiler is not forced by the standard to emit a warning (it tries its best to perform the conversion whenever possible). Compile with -Wconversion

g++ -Wconversion program.cpp

and you'll get your warning:

warning: conversion to 'int' from 'double' may alter its value [-Wfloat-conversion]

The typical warning flags -Wall -Wextra don't catch it since many times it is the programmer's intention to truncate double 's to int 's.

Live example here .

c++ automatically casts floats and doubles to integer literals by truncating them. so 3.3 becomes 3 when you call dmult(3.3,2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM