retrodev
retrodev

Reputation: 2393

Passing non-const arguments to const function parameters in C

I have a function that specifies a const parameter to indicate to the caller that it won't be modfied:

int func1(const char *some_string) 
{
    // Do something non-destructive with some_string
}

I pass a non-const variable as an argument to func1:

int func2(void)
{
    char *my_string = "my text";
    func1(my_string);
}

gcc reports:

warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

What is the correct way to deal with this situation? Creating a const copy of my_string seems a bit much, but simply casting seems like burying the warning.

Upvotes: 0

Views: 5459

Answers (3)

The error comes because the project is compiled with -Wwrite-strings extra warning. This warning is not enabled by default by any common warning options, -Wall, -Wextra because it can make even strictly conforming C programs produce diagnostics messages.

Namely

char *foo = "bar";

is a strictly conforming C fragment as such, "bar" being a non-modifiable array of type char [4]. Using char * for the type is not the best practice though, and const char *foo should use instead if possible. The -Wwrite-strings makes this not-the-best practice visible. It is just meant as an aide to write better programs but it as such doesn't uncover the real problems.

Upvotes: 0

Andrei Bârsan
Andrei Bârsan

Reputation: 3523

The issue you're having stems from your main function.

When you declare char *my_string = "my text";,you are creating a non-const pointer to a string literal. By design, string literals such as "my text" are immutable, and therefore const in the language. (In practice, the compilers usually put the string literals into a specific section of the executable which contains read-only memory, so attempting to modify the literal using the non-const pointer can lead to a segfault.)

By declaring a non-const pointer to the string literal, you end up with a pointer which you could use to modify the immutable string literal, which is considered undefined behavior in C.

See this question for more information.

The easiest way to solve this is to simply change char *my_string into const char *my_string.

Upvotes: 1

Yunbin Liu
Yunbin Liu

Reputation: 1498

You could use const char *my_string = "my text"; instead of char *my_string = "my text";

Upvotes: 0

Related Questions