Initialising int affects function return value

前端 未结 2 670
陌清茗
陌清茗 2021-01-13 20:08

Sorry for the vagueness of this question\'s title, but I\'m not sure how to ask this exactly.

The following code, when executed on an Arduino microprocessor (c++ co

相关标签:
2条回答
  • 2021-01-13 20:31

    Like all basic types of non-static storage duration, declaring but not defining an int does not cause default initialisation. It leaves the variable uninitialised. That does not mean i just holds a random value. It holds no (known, valid) value, and therefore you're not allowed to read it yet.

    Here's the relevant quote from the C++11 Standard, via Angew in the comments. This wasn't a new restriction, nor has it changed since then:

    C++11 4.1/1, talking about an lvalue-to-rvalue conversion (basically reading a variable's value): "If the object to which the glvalue refers is ... uninitialized, a program that necessitates this conversion has undefined behavior."

    Any read of an unitialised variable causes undefined behaviour, and so anything can happen. Rather than your program continuing to function as expected using some unknown default value, compilers can make it do absolutely anything, because the behaviour is undefined, and the Standard imposes no requirements on what should happen in such a scenario.

    In practical terms, that usually means an optimising compiler might simply remove any code that relies in any way on UB. There's no way to make a correct decision about what to do, so it's perfectly valid to decide to do nothing (which just happens also to be an optimisation for size and often speed). Or as commenters have mentioned, it might keep the code but replace attempts to read i with the nearest unrelated value to hand, or with different constants in different statements, or etc.

    Printing a variable doesn't count as 'checking it' as you think, so that makes no difference. There is no way to 'check' an uninitialised variable and thereby to inoculate yourself against UB. The behaviour of reading the variable is only defined if the program has already written a specific value to it.

    There is no point in us speculating on why particular arbitrary types of UB occur: you just need to fix your code so that it operates deterministically.

    Why do you want to use it uninitialised anyway? Is this just 'academic'?

    0 讨论(0)
  • 2021-01-13 20:41

    When you don't initialise the variable it has a random value, whatever was in the memory address, so while (i <=strlen(str)) is going to behave unpredictably. You should always initialise.

    (Visual Studio Debug configurations automatically initialise variables.)

    0 讨论(0)
提交回复
热议问题