Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a bad call with a const signature in C [duplicate]

Possible Duplicate:
why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

Why do I get a warning (gcc 42.2) with the following call of foo?

void foo(const char **str)
{
  (*str)++;  
}

(...)
char **str;
foo(str);
(...)

I understand why we cannot call a function that excepting a char ** with a const char **, but the opposite seems ok to me, so why the following warning?

warning: passing argument 1 of 'foo' from incompatible pointer type
like image 648
Guid Avatar asked Dec 06 '12 15:12

Guid


People also ask

Is Const valid in C?

Yes. const is there in C, from C89.

What is const type in C?

The const keyword allows a programmer to tell the compiler that a particular variable should not be modified after the initial assignment in its declaration.

Is Const part of function signature?

A function declaration tells the compiler the function's signature and return type. In the above example, the function's signature is F(int) . The constness of the function's parameter type is ignored, so both declarations are equivalent (See “Overloadable declarations”.)


1 Answers

It is wrong. There is no real room for arguing with the compiler here, since it's supported by the spec. Here's an example which explains exactly why it is wrong:

void func(const char **p)
{
    *p = "abc";
}

void func2(void)
{
    char *a;
    func(&a);
    *a = 'x';
}

If the compiler didn't spit out an error, your program would probably crash because you'd be overwriting a string literal (which is often marked read-only in memory).

So you cannot implicitly cast char ** to const char ** because it would allow you to remove the const qualifier from any value — basically, it would allow you to ignore const at will without an explicit cast.

The main reason the compiler gives a warning instead of an error is because lots of old code does not use the const qualifier where it would if the code were written today.

like image 141
Dietrich Epp Avatar answered Nov 11 '22 08:11

Dietrich Epp