I was reading the Wikipedia article about Undefined behaviour.
in C the use of any automatic variable before it has been initialized yields undefined behavior
However, this answer says, it is ok for character types. Is Wikipedia wrong here?
I was reading the Wikipedia article about Undefined behaviour.
in C the use of any automatic variable before it has been initialized yields undefined behavior
However, this answer says, it is ok for character types. Is Wikipedia wrong here?
In C (I have no idea about C++), the type unsigned char
is the only type that guarantees all possible bit representations have a specific value. There is no trap representation, no invalid values, no padding bits, no nothing (as can be in other types).
However it is a bad idea to make a program that relies on an unknown bit pattern for some reason.
Undefined behavior does not mean illegal or your program will crash here.
If you use an uninitialized variable (which happens if you allocate a primitive variable and don't assign a value to it, character types being one special kind of primitive types), the value is simply not determined. It can be anything. You might not bother the fact that it can be anything, because for example you could assign a value later, maybe only in some case.
However, when this becomes serious is when you read the value of the variable and make further decisions depending on this uninitialized value, for example in a condition:
int x;
if (x > 0) {
...
} else {
...
}
This will bring you here.
What the answer you linked says is that the following is perfectly fine:
int x;
if (someCase) {
x = ...
} else {
...
}
// later:
if (someCase) {
// read x
}