Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-qualifiers on function return type

Tags:

c

Given the following C source code:

const int foo(void)
{
    return 42;
}

gcc compiles without errors, but with -Wextra or -Wignored-qualifiers, the following warning appears:

warning: type qualifiers ignored on function return type

I understand that there's good reason in C++ to distinguish between const functions and non-const functions, e.g. in the context of operator overloading.

In plain C however, I fail to see why gcc doesn't emit an error, or more concisely, why the standard allows const functions.

Why is it allowed to use type qualifiers on function return types?

like image 207
Philip Avatar asked Aug 21 '12 09:08

Philip


People also ask

What are type qualifiers in C++?

In the C, C++, and D programming languages, a type qualifier is a keyword that is applied to a type, resulting in a qualified type. For example, const int is a qualified type representing a constant integer, while int is the corresponding unqualified type, simply an integer.

What is the use of type qualifier?

A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether: The value of an object can be changed. The value of an object must always be read from memory rather than from a register. More than one pointer can access a modifiable memory address.


2 Answers

Consider:

#include <stdio.h>

const char* f()
{
    return "hello";
}
int main()
{
    const char* c = f();

    *(c + 1) = 'a';

    return 0;
}

If const were not permitted on the return value then the code would compile (and cause undefined behaviour at runtime).

const is useful when a function returns a pointer to something unmodifiable.

like image 189
hmjd Avatar answered Sep 18 '22 18:09

hmjd


It's irrelevant if the value returned from the function is qualified as const.

You cannot change the value returned even if it wasn't qualified.

foo() = -42; /* impossible to change the returned value */

So using const is redundant (and normally omitted).

like image 45
pmg Avatar answered Sep 21 '22 18:09

pmg