-5

In C, inside a function, if we declare a variable and don't initialise it, it generates a garbage value and stores it in the variable.

Whereas in Java, it does not allow you to use a local variable without initialising in a method.

But the code below, when compiled and ran on online C compilers,

Idk why instead of generating garbage values, it is printing "123". (without quotes)

#include <stdio.h>

void f();

int main(){
  f();
  f();
  f();
}

void f(){
  int i;
  ++i;
  printf("%d", i);
}
Ankit Gupta
  • 512
  • 1
  • 6
  • 19
  • 2
    Undefined behavior for using the value of an object with automatic storage duration while it is indeterminate. – EOF Apr 11 '20 at 15:01
  • 1
    `1` `2` and `3` seem like "garbage" values to me. What value would *you* consider garbage? – abelenky Apr 11 '20 at 15:03
  • how can the same numbers be printed on every different compiler ?! – Ankit Gupta Apr 11 '20 at 15:05
  • Since `i` is uninitialized, it's probably picking up whatever happens to be at that memory address, and it looks like it's picking up the previous values, but that behavior cannot be relied on. Changing compilers, platforms, optimization levels, even compiler releases could change the behavior. If you want to make a counter, change the declaration of `i` to `static int i;` – Tom Karzes Apr 11 '20 at 15:06
  • Is there a requirement that different compilers on different platforms use different "garbage values"? **NO**. – abelenky Apr 11 '20 at 15:07
  • 1
    Also, if you call some other function in between the calls to `f`, the behavior will almost certainly change. – Tom Karzes Apr 11 '20 at 15:08

2 Answers2

1

Because of common implementations of C, an uninitialized value near the start of a C program is likely to be 0, so your subsequent ++i operations change it to 1 2 and 3.

However, take good note of this:

Just because it is likely to be zero does not guarantee it will be zero.

This is undefined behavior, and the values could correctly come out to be anything.

Community
  • 1
  • 1
abelenky
  • 63,815
  • 23
  • 109
  • 159
1

"I do not know why instead of generating garbage values, it is printing "123"."

When any expression in the program invokes Undefined Behavior, which is made by incrementing and printing the indeterminate value of i, the result/output does not need to be wrong, but there will never be a guarantee that it will be correct, which is a reason to never rely on any of such a code, does not matter if it prints the right values in one specific case.

Thus, you do not need to smash your head around finding a reason for that behavior.