0

I'm new to C and the gcc compiler. While exploring the language, I happened on some unexpected output while running the following code:

int total;
total += 6;
printf("%d", total);
double avg;
avg = 1.0;

In my experience, numbers between 32770 and 32773 are outputted on:

  • Multiple (but not all) online gcc compiler sites
  • Remote linux servers I use (gcc 5.4.0)
  • My own linux machine (gcc 9.4.0)

Oddly, this code will properly output 6 when the last line (avg = 1.0) is removed, as well as on certain machines running a gcc version that produces the unexpected output elsewhere.

Of course, the alternative lines int total = 0 and total = 6 fix the issue, but I'd like to know what's specifically going on here.

jooler
  • 1
  • 2

1 Answers1

1

In this code:

int total;
total += 6;

If you don't initialize variables, the compiler is free to initialize them to anything, or not initialize them at all. You may get zero, you may get a random value, or you may get memory which was initially used for something else, and is being reused.

If you care what the value of total is when the variable is defined, then change it like this:

int total = 0;
total += 6;

Then, total is guaranteed to be 6, no matter what. If you don't initialize it, then you're telling the compiler you don't care what the value is.

Nick ODell
  • 15,465
  • 3
  • 32
  • 66