Shaber
Shaber

Reputation: 61

uninitialized switchcase error in qt programming

This is my code for checking the laptop battery state. I am not getting this right, because the compiler gives me an error about the switch case:

UPower *u = new UPower(this);

    Battery *b;
    foreach (Battery *bat, *u->batteries()) {
        b = u->batteries()->value(bat->path());
    }
    ui->batteryProg->setValue(b->percentage());

    switch( b->state() ) {
        case Battery::FullyCharged:
            ui->batteryStatus->setText( tr( "Full" ) );
            break;
        case Battery::Discharging:
            ui->batteryStatus->setText( tr( "Discharging" ) );
            break;
        case Battery::Charging:
            ui->batteryStatus->setText( tr( "Charging" ) );
            break;
        default:
            ui->batteryStatus->setText( tr( "No Battery" ) );
            break;
    }
    ui->batteryframe->setVisible(true);

Here's the error output by the compilation process:

 make: *** [Makefile:2028: corebox.o] Error 1
 make: *** Waiting for unfinished jobs....
 coreaction/coreaction.cpp: In member function 'void 
 coreaction::batteryCheck()':
 coreaction/coreaction.cpp:114:25: warning: 'b' may be used 
 uninitialized in this function [-Wmaybe-uninitialized]
     switch( b->state() ) {
             ~~~~~~~~^~
 ==> ERROR: A failure occurred in build().
 Aborting...

What am I doing wrong??

Upvotes: 1

Views: 136

Answers (2)

Shaber
Shaber

Reputation: 61

solution

Battery *b = nullptr;
    foreach (Battery *bat, *u->batteries()) {
        b = u->batteries()->value(bat->path());
    }
    if (!b)
        return;

Upvotes: 1

Paul
Paul

Reputation: 158

This is the important part:

 coreaction/coreaction.cpp:114:25: warning: 'b' may be used 
 uninitialized in this function [-Wmaybe-uninitialized]
     switch( b->state() ) {
             ~~~~~~~~^~

It states that b may be used uninitialized which would be true if the loop is empty and therefore b never gets set.

foreach (Battery *bat, *u->batteries()) {
        b = u->batteries()->value(bat->path());
    }

Hope that helps. A solution would be to test for b before the switch-statement after initializing it to nullptr.

This is the important part, there is a difference between a nullptr and an uninitialized pointer.

Battery* b = nullptr; // nullptr
Battery* b;           // uninitialized

Upvotes: 2

Related Questions