How to find variables that should be constants in C?

So, I have this code:

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

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

And I ask my friend to take a look at the code, and he says: "You do not change this, and it would be really confusing if you did it, so do it const."

And that seems like a good idea, therefore:

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

or even:

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

And now I think, I bet that there are many other places where I could do this, and I bet that the compiler would be better off finding them than me.

Any ideas how I ask this question? (gcc is preferable, but no problem using another compiler or transfusion tool if they work on unix).

+5
source share
2 answers

GCC has a flag offering useful attributes like const

-Wsuggest-attribute = [pure | const | noreturn | format] Warn about cases where adding an attribute may be useful. Attributes are currently supported below.

-Wsuggest-attribute = pure
-Wsuggest-attribute = sop
-Wsuggest-attribute = noreturn
Warn about functions that might be candidates for pure, const, or noreturn attributes. Only for the compiler warns about functions visible in other compilation units or (in the case of pure and const) if it cannot prove that the function returns as usual. A function returns normally if it does not contain an infinite loop or return abnormally, throwing, causing an interrupt or capture. This analysis requires the -fipa-pure-const option, which is enabled by default with -O and higher. Higher optimization levels improve analysis accuracy.

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

+4
source

const extends. In fact, this often becomes a problem and is called "const poisoning." The problem is a function like strchr (), which can be called with a const pointer or with a variable. But if it returns const *, the string cannot be modified with a pointer, which is often exactly what you want to do.

But if you just make your const data constant at a point right after you read it in / initialize it, the compiler will throw you errors every time you go to a non-contextual context.

-2
source

Source: https://habr.com/ru/post/1268112/


All Articles