V2009. Consider passing the 'Foo' argument as a constant pointer/reference.


This diagnostic message was added on users' request. The analyzer suggests that a function argument should be made a constant one. This warning is generated in the following cases:

  • The argument is an instance of a structure or a class which is passed into the function by reference but not modified inside the function body;
  • The argument is a non-constant pointer, but it is used only for data reading.

This diagnostic may help you in code refactoring or preventing software errors in the future.

Consider the following sample:

void foo(int *a)
{
  int b = a[0] + a[1] + a[2];
  .... 'a' variable is not used anymore
}

It is better to make the 'a' pointer a constant one. First, it makes it clear that the argument is used for data reading only. Second, making the 'foo()' function constant enables us to make other variables and functions constant too.

This is the fixed code:

void foo(const int *a)
{
  int b = a[0] + a[1] + a[2];
  .... 'a' variable is not used anymore
}

Note. The analyzer may make mistakes when trying to figure out whether or not a variable is being modified inside the function body. If you have noticed an obvious false positive, please send us the corresponding code sample for us to study it.

Messages generated by the analyzer may sometimes seem pretty strange. Let's discuss one of these cases in detail:

typedef struct tagPOINT {
    int  x, y;
} POINT, *PPOINT;

void foo(const PPOINT a, const PPOINT b) {
  a->x = 1;     // Data can be changed
  a = b;        // Compilation error
}

The analyzer suggests that the pointer should be made constant. It seems strange, since there is the keyword 'const' in the code. But 'const' actually indicates that the argument is constant, while the memory addresses the pointers refer to are available for modification.

To make the data themselves constant, we should do the following thing:

....
typedef const POINT *CPPOINT;

void foo(const CPPOINT a, const CPPOINT b) {
  a->x = 1;     // Compilation error
  a = b;        // Compilation error
}

Bugs Found

Checked Projects
364
Collected Errors
13 504