When I am running Coverity analysis shows error in function below.
void initalizeStatement(sqlite3* db, const char* query)
{
// statement shall not be reuesed!
if (_valid) _valid = false;
else
{
sqlite3_stmt* stmt = NULL;
auto result = sqlite3_prepare(db, query, -1, &stmt, NULL);
if(SQLITE_OK != result)
{
DLT_LOG(dltContextSARMBUtils, DLT_LOG_ERROR,
DLT_STRING("[Statement::initalizeStatement()] sqlite3_prepare failed. status code : "),
DLT_INT(result),
DLT_STRING(", query : "),
DLT_STRING(query));
}
else //all good!
{
_valid = true;
_stmt = stmt;
_db = db;
}
}
}
Error I am seeing is as below:
<testcase name="[45] MISRA C++-2008 Rule 7-1-1 | misra_cpp_2008_rule_7_1_1_violation" time="0">
<failure message="The variable `query` has a non-const type, however its value is never changed. Consider adding a const qualifier to the variable type."> MBUtils::Statement::initalizeStatement(sqlite3*, char const*) </failure>
Why is this error shown if it is already having const
type?
Solution: Add const to the declaration
MISRA C++ 2008 Rule 7-1-1 reads, in its entirety, "A variable which is not modified shall be const qualified." (The standard is not freely available so I can't link to it.) Additionally, the example given in the standard makes it clear that this rule applies to parameters as well as local variables.
In your example code,
query
is not modified, hence it must beconst
qualified to comply with this rule:In your original code,
query
is declared to point to something that isconst
, but is not itselfconst
.How to read C declarations
As the syntax for C/C++ declarations can be a bit confusing, my advice is to read them from right to left. So the original declaration:
would be read as "query is a pointer to a character that is constant". The declaration in my suggested fix:
would be read as "query is a constant pointer to a character that is constant".
Style opinion
Incidentally, if this were my code (and I had to comply with MISRA), I would actually write it as:
This reverses the order of
char
andconst
at the beginning, so it now reads as "query is a constant pointer to a constant character", which is a more natural English description.