Warning when passing a non-constant parameter to a function that expects a const parameter. Is there a better way?

I am trying to pass a parameter to a function and point out that the parameter must be accepted by const by the receive function.

I realized that the following code example shows the only way to guarantee that the test function can be called using the argv variable, which is not declared as const.

 void test(const char * const *arr); int main(int argc, char *argv[], char *env[]) { test(argv); } void test(const char * const *arr) { } 

However, gcc gives me a warning, for example the following:

 E:\Projects\test>gcc -o test test.c test.c: In function 'main': test.c:5:2: warning: passing argument 1 of 'test' from incompatible pointer type [enabled by default] test.c:1:6: note: expected 'const char * const*' but argument is of type 'char **' 

It makes me think that what I'm doing here is somehow wrong. Is there a better way to pass a parameter to a function and indicate that it should be considered a const function by a receive function?

+4
source share
2 answers

The C FAQ explains why there is safe protection in C when converting pointers to non from const to const . I think in your case of a double const target, the problem that is described there will not arise. So C ++ has a laid-back rule that will allow you to the implicit conversion you are asking for. Unfortunately, for C, the standards committee found the rule from C ++ too complicated, so you would need to point to the expected type.

+11
source

You can use it, for example:

 void test(const char * const *arr); int main(int argc, char *argv[], char *env[]) { test((const char * const *)argv); } void test(const char * const *arr) { } 

This will make the warning go away. This is normal if you can really consider argv as const char * const * in your function.

+1
source

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


All Articles