CWARN.NOEFFECT.SELF_ASSIGN

Ineffective self-assignment

The CWARN.NOEFFECT.SELF_ASSIGN checker flags instances in which an expression that corresponds to a variable is assigned to itself.

Vulnerability and risk

Self-assignment doesn't have any effect, so it's probable that the design intent isn't being accomplished. Even if it isn't an error, the self-assignment may indicate a larger error in the code.

Vulnerable code example 1

1  class A {
2      int x;
3    public:
4      A() : x(x) {} 
5  };

Klocwork flags line 4, in which the self-assignment occurs.

Fixed code example 1

class A {
    int x;
  public:
    A(int x) : x(x) {} 
};

In the fixed example, the assignment expression is correct.

Vulnerable and fixed code example 2

1  class A {
2      int i;
3      char c;
4      bool b;
5    public:
6      A(int i, char c) {
7        this->i = i;   
8        this->c = c;  
9        this->b = b;  
10     }  
11 };

In this example, Klocwork flags line 9, which demonstrates self-assignment, but doesn't flag lines 7 or 8, in which the assignment expressions are correct.