-1

Recently I have installed Ubuntu and obviously I am compiling my C code in gcc. I came across the following code :

#include <stdio.h>
main()
{
    int i = 10,j = 20, k;
    printf("i=%d  j=%d  k=%d\n", i, j, k);
}

The output is coming as ::

i=10  j=20  k=0

But as far as I know that the output for the value of k should be a Garbage value since it has not been initialized.

Is there something that I am missing here?

anand mishra
  • 900
  • 1
  • 11
  • 30
Dibakar Bose
  • 100
  • 1
  • 8

2 Answers2

2

You cannot expect anything from the program you posted, 0 is a perfectly possible garbage value.

Also, main() must have a return value and it must be int.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Yeah I know this is just a strange program.. But the confusing part is does the Garbage value depends on system to system.? I mean my system is giving 0 everytime I run it, But in other system different Garbage Value everytime it is run. – Dibakar Bose Jan 01 '16 at 17:12
  • @DibakarBose garbage is garbage, please don't try to read anything into it. At worst, the `0` will trick you into ignoring the compiler warning under the delusion "Never mind, that worked". The value `0` occurs frequently, consider too that the most common house number in an address database is `1`. Why? Because every street has that number. – Weather Vane Jan 01 '16 at 17:15
  • Thank you very much.... I will keep this in mind... :) – Dibakar Bose Jan 01 '16 at 17:23
2

It's undefined behavior, so anything is possible, including 0 to be printed.
How is 0 not a garbage value?

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • In some other system whenever this is run different output is coming. I mean to say that Different Garbage value is coming,.. But in my case it is staying constant.. Is there any specific reason for this behaviour? – Dibakar Bose Jan 01 '16 at 17:10
  • 1
    @DibakarBose Of course there is **some**, OS-specific reason but from the standard's perspective it is completely undefined and random. Your variable is uninitialized, so it is undefined behavior and **anything might happen**. – cadaniluk Jan 01 '16 at 17:11
  • Thank you very much for clearing my confusion... I appreciate that... – Dibakar Bose Jan 01 '16 at 17:23