Why does that happen in C?

1155 views c
5

I know I shouldn't define any function like that. But I like to try the limits, so I wrote some code like that:

#include <stdio.h>

void func(a)
{
    printf("%d\n", a);
}

int main()
{
    func();
    func();
    func();
    return 0;
}

I really wasn't looking for any outputs, but the one I saw was very odd.

The output is

1
0
0

Why? Where did those 1's or 0's came from?

(I'm using CygWin & Eclipse duo btw.)

answered question

You're pulling garbage off the stack. The value could be anything. This is undefined behavior.

When you asked "where did those 1's or 0's came from?", you just answered your question.!!

2 Answers

5

Your program is invalid.

gcc 8.2 complains:

$ gcc -Wall -Wextra -pedantic -std=c17 t.c
test.c: In function ‘func’:
test.c:3:6: warning: type of ‘a’ defaults to ‘int’ [-Wimplicit-int]
 void func(a)

Since C99, all functions require their arguments to have valid types (there used to be "implicit int" rule - function argument/return types are assumed int if not specified). But your program is not valid in C89 either because you don't actually pass any argument. So what you see is the result of undefined behaviour.

posted this
12

When you don't define type for the variables int is taken as default type by compiler.

warning: type of 'a' defaults to 'int' [-Wimplicit-int]
 void func(a)

Hence it is printing indeterminate values which int a contains.

posted this

Have an answer?

JD

Please login first before posting an answer.