Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
Dante1234 Avatar asked Apr 23 '15 23:04

Dante1234


Video Answer


2 Answers

double's are implicitly convertible to ints (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.

like image 122
vsoftco Avatar answered Oct 11 '22 08:10

vsoftco


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

like image 37
finagle29 Avatar answered Oct 11 '22 07:10

finagle29