Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: How come adding an int to an empty variable results in random numbers

Tags:

c

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?

like image 529
relee24 Avatar asked Dec 15 '16 16:12

relee24


1 Answers

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();))

like image 88
PSkocik Avatar answered Sep 28 '22 18:09

PSkocik