Consider:
int a[100];
Is it possible for the uninitialized value in a[i]
(where 0 < i < 100) to be negative?
Consider:
int a[100];
Is it possible for the uninitialized value in a[i]
(where 0 < i < 100) to be negative?
Yes, why wouldn't it ? Theses bits can be anything and the sign of an integer is usually its MSB (most significant bit). If that bit is 1
, then the int
will be considered negative.
I see little point of knowing that though. You can't rely on garbage data as it's undefined behavior.
The answer is that it can be any value.
However don't consider using it for anything. This program :-
void func()
{
int a[100];
if (a[10] == 0 || a[10] != 0) {
std::cout << "The value is either zero or not zero\n";
}
}
It is entirely possible that your compiler won't print the message because accessing an initialized value is undefined behavior and the compiler can do anything including stuff like this. And increasingly compiler do.
I think if you understood the meaning of garbage value, you wouldn't ask this question.
When you declare a variable, a piece of memory is allocated to it. This memory could be anything that the operating system considered free, and hence could contain bits that were written by some previous program to which this same memory was allocated.
The previous program could have been anything (a music player, a game you were playing, an image that you viewed, etc.). Thus that data is just a bunch of bits, now to be used as integer in your code. So your compiler will read it as an integer, which is the reason why it could be negative if the first bit is 1
as mentioned by AlexG