Ramy Sameh
Ramy Sameh

Reputation: 301

const keyword before a function in C

I want to know what a "const" keyword before a function in 'C' does.

For example:

extern const int func1(int x[], const struct dummy_s* dummy)

Thanks in advance

Upvotes: 0

Views: 244

Answers (3)

Lundin
Lundin

Reputation: 213513

In standard C, your code will not compile. You are not allowed to omit the return type of a C function.

In an older, obsolete version of C known as C90, you were allowed to omit the return type, in which case it would default to int. In that old version of C, your code would be equal to:

extern const int func1(int x[], const struct dummy_s* dummy);

The next question then is, does it ever make sense to return const int from a function, rather than just int? No, it doesn't... because the returned variable is always a hard copy placed on the stack. It is not a lvalue and the function is executed in runtime anyhow, there is no reason why this value needs to be const.

Upvotes: 2

Drax
Drax

Reputation: 13278

If you turn on warnings you will have two:

warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
warning: 'const' type qualifier on return type has no effect [-Wignored-qualifiers]

which easily allows you to conclude that this:

extern const func1(int x[], const struct dummy_s* dummy)

is basically the same as:

extern int func1(int x[], const struct dummy_s* dummy)

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

It has no any sense. It seems that it is some old code that was valid when C allowed implicit return type int if the return type is not specified explicitly. But in any case the return value is not an lvalue and can not be changed. So the const qualifier is superfluous.

Upvotes: 2

Related Questions