سؤال

I got some code to analyze and I can't realize why this expression always give me the same result, the letter "b" in this example.

unsigned char ucVal2;
ucVal2 |= 0x62;

I always thought that when you don't define a variable, its value is non-deterministic.. So, in this case, I was supposing that the value of ucVal2 would have been SOMETHING OR 0x62, but the execution always show me that ucVal2 is 0x62, just like SOMETHING is always 0x00.

هل كانت مفيدة؟

المحلول

That might just be luck. Or your particular compiler and/or OS might guarantee that memory is initialized to 0, even though the C language itself doesn't.

According to the standard, the value of ucVal2 is undefined and the above code is not portable. Ther eis nothing special about using the |= operator like this that in some way affects the fact that it's undefined.

نصائح أخرى

If ucVal2 is defined at file scope (ie a "global") then it will always be initialized to 0. If it's declared at function scope, then it won't be, and its value will be random.

non-deterministic is not the same thing as random.

Just because there are no guarantees about the value of an uninitialized variable doesn't mean it you cannot reasonably guess what the value is.

Most memory ends up being zero after a computer starts up. Until a process writes to it, it will continue to be zero. When your program declares this uninitialized variable, the value is most likely still zero. But you cannot be assured that it will be zero.

You absolutely cannot rely on the value being zero. Just because the variable starts at zero for one thousand tests in a row, for the thousand-and-first test, it may be something completely different.

Accessing the contents of an uninitialized variable is undefined behavior. Meaning it could be non-deterministic junk, deterministic junk or zero. The program is even free to crash and burn when you access it, although on most systems that is unlikely.

Think of it as if blindly sticking your hand into a public garbage bin: it can be empty, it could contain more or less disgusting garbage, there could be a gigantic rat inside biting your hand off. There is no guarantee of what you will come up with.

Trying to understand why a certain kind of undefined behavior gives a certain result isn't particularly meaningful, it usually yields little or no useful knowledge.

If we are to guess, then the junk you have there on the stack is a left-over from some program pre-initialization code, or previously executed functions. In such a case, the nature of the junk will likely be of a deterministic nature.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top