I’d done a test build of our code with the clang compiler, and tried out its static analyzer. It politely pointed out that the code like the following was likely wrong:
struct cpuinfo
{
int pkg_id ;
int core_id ;
int smt_id ;
int logicalId ;
void init( int pkg, int core, int smt, int logical )
{
pkg_id = pkg ;
core_id = core ;
smt_id = smt ;
logical = logicalId ;
}
} ;
$ clang --analyze -c cpuinfo.C
cpuinfo.C:13:8: warning: Value stored to 'logical' is never read
logical = logicalId ;
^ ~~~~~~~~~
1 warning generated.
In fixing this, I made two changes. The first was const’ing the parameters:
void init( const int pkg, const int core, const int smt, const int logical )
If that had been done, this runtime error wouldn’t have been possible:
clang -c cpuinfo.C
cpuinfo.C:13:18: error: read-only variable is not assignable
logical = logicalId ;
~~~~~~~ ^
1 error generated.
Had the member variables been named consistently I doubt this error would have been made. It would have been too obvious that something was wrong:
void init( int pkg, int core, int smt, int logical )
{
pkg_id = pkg ;
core_id = core ;
smt_id = smt ;
logical = logical_id ;
}
so, I also followed up the const’ing, done as a preventive maintanance action, with a search and replace to fix up the logicalId member variable:
s/logicalId/logical_id/g
and then made the actual fix in question.
I could have fixed the code only changing the one assignment line in question. The final fix ended up just touching 5 additional lines, since the code was self contained.
I got asked by the original author why I did the const’ing part of this change. It suprised me to get that question, and reminded me of the time where I was once met with a significant objection to using “new-fangled C++” features like ‘const’ in our code.
At the time, most of our code was very C-like, despite being compiled with a C++ compiler. The component owner said that he’d only consider using const if I could prove there was a performance benefit to doing so. I don’t think I ever proved that to him, but I think here’s a nice demo of why it’s a good habit in general to use const whenever there isn’t explicit intention to allow modification.