Transfer int to const int?

I am reading a C code base and I found a snippet that looks something like this:

void foo(int bar) { const int _bar = bar; ... } 

The author then uses _bar in the rest of the code. Why is this done? Is this an optimization, or is there some other reason?

+4
source share
3 answers

Presumably the author does this to avoid accidental assignment.

If the parameter does not change from the function input, the author can put const in the param signature, as in void foo (int const bar) { ... } .

+4
source

The author then uses _bar in the rest of the code.

If _bar used through out and does not use a function parameter, I would qualify the function parameter with const .

 void foo( const int bar ) { // use bar but modifications to bar itself are not allowed. } 
+6
source

Since C passes arguments by value, there is no difference between

 void foo(int bar); 

and

 void foo(const int bar); 

regarding the call code.

Thus, const-qualifying for a parameter without a pointer probably makes an internal implementation detail of an internal public API.

Another solution would be to declare a function without const in the header and only add it to the definition (as Oli Charlworth also suggests in the comments), i.e.

 // in header file extern void foo(int bar); // in source file void foo(const int bar) { // ... } 

which, to my knowledge, is legal due to the last sentence of C99 6.7.5.3 ยง15.

+3
source

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


All Articles