Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find variables that should be constants in C?

Tags:

c

So, I've got this code:

uint8_t* pbytes = pkt->iov[0].iov_base;

that creates a pointer to the start of an ethernet packet in a structure.

And I ask my friend to look at the code, and he says: "You're not modifying that, and it would be really confusing if you did, so make it const".

And this seems like a good idea, so:

const uint8_t* pbytes = pkt->iov[0].iov_base;

or even:

const uint8_t * const pbytes = pkt->iov[0].iov_base;

And now I am thinking, I bet there are loads of other places where I could have done that, and I bet the compiler is going to be better at finding them than me.

Any ideas how I ask it the question? (gcc preferred, but no problems using a different compiler or a linting tool as long as they will run on unix).

like image 209
John Lawrence Aspden Avatar asked Oct 29 '22 07:10

John Lawrence Aspden


1 Answers

GCC has a flag to suggest beneficial attributes like const

-Wsuggest-attribute=[pure|const|noreturn|format] Warn for cases where adding an attribute may be beneficial. The attributes currently supported are listed below.

-Wsuggest-attribute=pure
-Wsuggest-attribute=const
-Wsuggest-attribute=noreturn
Warn about functions that might be candidates for attributes pure, const or noreturn. The compiler only warns for functions visible in other compilation units or (in the case of pure and const) if it cannot prove that the function returns normally. A function returns normally if it doesn’t contain an infinite loop or return abnormally by throwing, calling abort or trapping. This analysis requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis.

Src: http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

like image 78
Zakir Avatar answered Nov 14 '22 04:11

Zakir