0

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

Ramy Sameh
  • 271
  • 4
  • 13

3 Answers3

4

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)
Drax
  • 12,682
  • 7
  • 45
  • 85
  • Don't just turn your warnings on, compile your C code as standard C. `gcc -std=c11 -pedantic-errors -Wall -Wextra`. You will now get errors, not just warnings. – Lundin Oct 17 '14 at 14:26
  • @Lundin that depends entirely on which standard the user is using. If they are using C89 it should be perfectly valid code. You cannot assume every program has been made since 2011 :) – Vality Oct 17 '14 at 14:57
2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396