-1

Is this code undefined behaviour ?

Specifically this ? "while (Thing* x = getNext(x))" does the x get initialised to zero because of a rule in the standard or is it just lucky or the compiler is doing it anyway but shouldn't be relied upon?

#include <iostream>

struct Thing {

};

Thing* getNext(Thing* thing)
{
    std::cout << "thing:" << thing << "\n";
    return thing;
}

void test()
{
    while (Thing* x = getNext(x))
    {

    }
}
Conrad Jones
  • 236
  • 3
  • 9

3 Answers3

1

This program exhibits undefined behavior, by way of accessing a value of uninitialized variable. If you observe zero being printed, it's only by accident.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
1

Is this uninitialised variable usage undefined behaviour

Yes.

The behaviour of reading an indeterminate value is undefined. This code copy initialises the argument thing using x which hasn't yet been initialized, thus having an indeterminate value and thus behaviour is undefined.

Is this code undefined behaviour ?

Yes.

Specifically this ? "while (Thing* x = getNext(x))"

Yes, specifically this has UB.

does the x get initialised to zero because of a rule in the standard

No. There is no such rule that would say x would be zero initialised in this context.

or is it just lucky or the compiler is doing it anyway but shouldn't be relied upon?

The behaviour is undefined. If it was the behaviour of the program that alerted you to the conclusion that it might be undefined, then you could consider yourself to have been lucky. You can improve your luck by enabling compiler warnings:

warning: 'x' may be used uninitialized in this function [-Wmaybe-uninitialized]
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Might want to emphasise that, in "this context", `x` is a variable of automatic storage duration. If `x` was of static storage duration (another context), it would be zero-initialised - and the OP is incorrectly assuming zero-initialisation always applies. – Peter Jan 06 '19 at 05:18
  • No it wasn't the behaviour of the program that alerted me, it is was being set the zero which I though was incorrect or just luck on what was at memory there at the time hence the question – Conrad Jones Jan 06 '19 at 10:50
0

Is this code undefined behaviour ?

Yes because your program is accessing an uninitialized variable.

Compile program with -Wall -Wextra options and you will find that compiler is giving this warning message:

prg.cpp:17:31: warning: variable 'x' is uninitialized when used within its own initialization [-Wuninitialized]
    while (Thing* x = getNext(x))
H.S.
  • 11,654
  • 2
  • 15
  • 32