dylnmc
dylnmc

Reputation: 4010

Why does -o with gcc change output

I was playing around with C on my Mac OS X (version 10.6.8); this is the small program to test what happens when you declare and int but don't initialize it:

#include <stdio.h>

int main() {
    int a;
    printf("\n%d\n\n", a); 
}

When I do gcc -std=c99 test.c; ./a.out, I get a predictable result: the max for an unsigned int (32767). However, something strange happens when I use the -o using gcc. When I do gcc -std=c99 test.c -o test.out; ./test.out I get something else: 0.

It doesn't matter what I name the file or how I compile it, I have figured out. If the name is not a.out, then I get 0. When the name is a.out I get either the largest uint type or some other larger number.

Contrary to some thoughts below, the number is semi-random (mostly largest uint but sometimes a larger number) only when the compiled file is a.out which is really weird. It could just be my computer; or, perhaps, I have luckily - or unluckily - received the same results 30 times in a row.

Upvotes: 2

Views: 114

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263237

The output of your program is meaningless, and is likely to be inconsistent from one run to the next.

Strictly speaking, your program has undefined behavior, since it reads the value of an object that has never been initialized or assigned to. That means that the C standard says nothing at all about what it will do. (The standard joke is that it can, in principle, make demons fly out of your nose; of course that's not going to happen, but if it did it wouldn't violate the rules of the C language.)

In practice, what's likely to happen is that the value printed will be whatever garbage happened to be in memory when your program started running. Using or not using -o when you compile the program may or may not have any effect. Likewise, the phase of the moon at link time may or may not have any effect.

People sometimes refer to this kind of garbage as "random", but that word has a specific statistical meaning. The value printed is arbitrary. It might happen to be the same every time you run the program, it might sometimes be 0, or anything else.

You wrote:

I get a predictable result: the max for an unsigned int (32767).

In fact, the maximum value for an unsigned int is at least 65535, and is more likely to be 4294967295. (See UINT_MAX, defined in <limits.h> for the actual value for your system). But that doesn't really matter; 32767 is as valid as any other garbage value.

(If you have defined a at file scope, or with the static keyword, it would have a well-defined initial value of 0. "Automatic" variables (those defined inside a function definition without the static keyword) have no defined initial value.

Upvotes: 5

Related Questions