Arturobot
Arturobot

Reputation: 11

An uninitialized variable may have an undefined value, but does that undefined value have the same data type?

Say we declare in C:

int a;

Its value is undefined (let's forget those compilers that set zero by default). But does this undefined value still have the data type of the variable (integer)?

So it could be that a=19382, a=23, a=-33332... but not a=33.2?

This sounds pretty logic to me, but not sure.

Upvotes: 1

Views: 110

Answers (4)

If an ordinary int is declared outside of functions, it will be initialized to 0. That's guaranteed by the C standard, and if your compiler (in practice the runtime library that the compiler links it with) does not set it to zero, then it has a seroius bug.

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf Section 6.7.9 paragraph 10.

If it's declared inside of a function, it'll have an indeterminate value, and accessing it might result in the dreaded undefined behavior.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

When it boils down to the bitwise representation of any variable, only by looking at that level, you cannot tell whether it is an int, float or whatever. That is why, the associated data type of a variable is required to understand and represent the type.

So, when a variable has indeterminate value, it is indeterminate. The point whether it is of the same type to the variable, does not make much sense, IMHO.

Just to make a point (not strictly speaking), you don't have any means to check the value of an uninitialized variable, as, trying to use (read) the value will generate undefined behaviour.

Upvotes: 4

user2371524
user2371524

Reputation:

The value is undefined, so using it is undefined behaviour. It could be an int, but it's also possible to have a bit pattern that isn't a legal representation for any int.

In practice, it's unlikely to have bit patterns that aren't legal representations of int, but doesn't guarantee you anything about it.

It can however never be a different type, because the type you give it determines how the bit pattern stored is to be interpreted.

Upvotes: 2

Tom Tanner
Tom Tanner

Reputation: 9354

As you have left it uninitialised, although a will consume the same amount of memory as an initialised int, the contents are indeterminate.

The compiler has to treat it as an int, so it could have any integer value. It can't be 33.2 because that isn't an int. It could however on some architectures happen to contain a 'trapping value' which would cause an error whenever you tried to access 'a'. Offhand, I can't think of any examples for an int, although floating point numbers do have values called 'signalling NANs' and some architectures will trap if you try load an invalid pointer into an address register.

Upvotes: 5

Related Questions