Most answers focus on technical reasons why you get the results you see. However, for beginners in C, they are probably not very useful answers, as they are a little difficult to understand without experience with C.
A softer explanation is that you need to understand that in C there are some rules that you must follow, and you need to keep promises. If you decide not to follow these rules, the compiler can do whatever it wants. This is what we call undefined behavior.
In your code: int add();
you promised the compiler that there is a function somewhere that returns an int
that takes some indefinite number of arguments.
Then you defined a function to take exactly two arguments. So, now you (in a certain sense) promised that the add
function will work correctly if you pass exactly two arguments (of type int
).
Later you call the add(3);
function add(3);
one argument. Since you passed only one argument to a function that is defined as exactly two, the compiler can do whatever it wants (in this case, return random numbers). He can do this because you have broken your promise that you need to pass two add
arguments.
As a rule, in order to catch these problems earlier (i.e., the compiler can warn us when we are going to do something stupid), we use more stringent definitions for functions.
Contrast a
with b
, c
, d
, which are more strict.
int a(); // a takes ??? arguments int b(void); // b takes exactly zero arguments int c(int x); // c takes exactly one argument int d(int x, int y); // d takes exactly two arguments
source share