New to C, when I run this code - something unexpected happens:
#include <stdio.h>
int add();
int main(void)
{
printf("%d\n",add(3));
}
int add(int i, int j)
{
return i+j;
}
I understand that I am not providing a second parameter to the add function. Out of curiosity though, can anyone tell me why calling the function with only 1 parameter supplied continues to return random numbers, such as 2127001435...612806891...-395221029?
If you break the rules of the language and the program compiles, its behavior is undefined (i.e., anything can happen).
int add();
tells the compiler to allow you to call add
with anything, but you still
must ensure that if the function definition accepts two ints
, you will call it with exactly two ints
.
Declarations with empty parameters are sometimes useful, but in 99% of cases you want to avoid them.
If you replace the declaration with this one
int add(int, int);
the compiler should save you from, or at least warn you about, your error.
(Additionally, declarations with typed parameters will make the compiler convert unfitting parameters if it can (e.g., if you were to call your add
function with a long
, then with the typed declaration, the long
argument will get implicitly converted to int
. This won't happen if the declaration is int add();
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With