-5

My code is

bool* old;
*old = false;
bool* ne;
*ne = true;

And the error is:

benchmarks/tpcc_txn.cpp:657:6: error: ‘old’ is used uninitialized in this function [-Werror=uninitialized]
 *old = false;
benchmarks/tpcc_txn.cpp:659:5: error: ‘ne’ is used uninitialized in this function [-Werror=uninitialized]
 *ne = true;
 ~~~~^~~~~~

It does not make any sense to me since I just declare it and tries to assign a value to it.

t.niese
  • 39,256
  • 9
  • 74
  • 101
Jibo
  • 11
  • 3
  • 9
    Ask yourself: With `bool* old;`, what object does `old` actually point to? – NathanOliver Mar 20 '20 at 16:38
  • https://stackoverflow.com/questions/12958931/warning-x-may-be-used-uninitialized-in-this-function – Nick is tired Mar 20 '20 at 16:42
  • 1
    `*old = false` is not assigning a value to the pointer. It's assigning a value to the `bool` the pointer points to. In this case, `old` wasn't made to point to any specific `bool` yet which is what the error is trying to tell you. – François Andrieux Mar 20 '20 at 16:52
  • There is a difference between a mistake that can be fixed by changing only a few characters and a typo. One was intentional, the other was not. The close reason seems wrong to me. – François Andrieux Mar 20 '20 at 16:53

1 Answers1

4

I just declare it and tries to assign a value to it.

No, you don't try to assign any value to it. What you try to do is indirect through the pointer and assign a value to the pointed object:

*old = false;
^
this here is the indirection operator

But behaviour of indirecting through an uninitialised pointer is undefined. The pointer doesn't point to any object that could be assigned.

What you must do is assign the value of the pointer, so that it points to some object. For example:

bool b;
bool* old;
old = &b;
*old = false;

Or you can simply initialise it directly:

bool* old = &b;
eerorika
  • 232,697
  • 12
  • 197
  • 326