Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

gcc

constants

I am trying to pass a parameter to a function, and indicate that the parameter should be considered const by the receiving function.

It was my understanding that the following code example shows the only way to ensure that the test function can be called with 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 such as 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 **'

This leads me to believe that what I am doing here is somehow wrong. Is there a better way to pass a parameter to a function, and indicate that it should be considered const by the receiving function?

like image 305
tsteemers Avatar asked Oct 20 '12 20:10

tsteemers


1 Answers

The C FAQ explains why in C there is a safe guard when converting a pointers to non-constto const. In your case of a doubly const qualified target pointer the problem that is described there wouldn't occur, I think. So C++ has a relaxed rule that would allow the implicit conversion that you are asking for. Unfortunately for C the standards committee found the rule from C++ too complicated, so you'd have to cast your pointer to the expected type.

like image 177
Jens Gustedt Avatar answered Nov 15 '22 06:11

Jens Gustedt