From my C++ textbook
an important feature of function prototypes is argument coercion - i.e, forcing argument to the appropriate types specified by the parameter declaration. For example, a program can call a function with an integer argument, even though the function prototype specifies a double argument - the function will still work correctly.
So i've tryied
#include <iostream>
// void foo(double);
void foo(double a) {
std::cout << sizeof(a) << std::endl;
}
int main (void){
int a = 1;
std::cout << sizeof(a) << std::endl;
foo(a);
return 0;
}
and with or without prototype it prints correctly first 4 then (inside function) 8.
Is my compiler that checks function definition in absence of prototypes (that may be not strict C++ standard, but useful too) or I have missed something?
Everything is as it should be here. Consider what you are outputting with your sizeof
call. You are outputting the size of the variable. Now what you have to understand is when you pass a
to your function foo
, a
is implicitly converted to a double
. The double
has the same value as the int
, but they are different types. The size of the int
is 4 bytes and the size of the double
is 8 bytes on your architecture.
Basically, what your textbooks means when it says the compiler will force arguments to the appropriate types specified by the parameter declaration is that it will look at your int a
and find what it would be as a double (It would be 4 in both cases). The compiler does this because it sees that the function foo
requires a double
but foo
is getting an int
. It does not change the type of a
in your main function. a
in main
is always an int
and a
in your foo
function is always a double
.
See: http://en.cppreference.com/w/cpp/language/implicit_cast for more on implicit conversion.