How to avoid Klockwork warning on initialization and assignment in C++

636 Views Asked by At

I am running static code analysis and found warnings.

For the below code snippet I get warnings as specified in the code. Is there a workaround to implement following code to resolve warnings?

int foo(bool cond)
{
    int var = 0; // Value of "var" never used after initial
    if(cond){
       var = 10; // Value of "var" never used after assignment
    }
    else{
       var = 20; // Value of "var" never used after assignment
    }
    return var;
}

void main(){
    cout << foo(true);
    return;
}
1

There are 1 best solutions below

0
Toby Speight On

The obvious thing to do is to remove the initial dead assignment:

int foo(bool cond)
{
    int var; // Declare, but don't initialise
    if (cond) {
       var = 10;
    } else {
       var = 20;
    }
    return var;
}

Or (better), eliminate the variable entirely:

int foo(bool cond)
{
    return cond ? 10 : 20;
}