In C, is it legal to add `const` only in function definitions, not declarations?

Adds additional qualifiers constto function arguments permitted by the standard, for example, as follows:

foo.h:

int foo(int x, char * data);

foo.c:

// does this match the prototype?
int foo(const int x, char * const data) {
    // this implementation promises not to change x or move data inside the function
}

GCC accepts it with -std=c99 -Wpedantic -Wall -Werror, but this does not necessarily match the standard.

This answer shows that the C ++ standard allows this - is this acceptable for the C (99) standard?


Here is another question here and a good answer here for C ++

+6
source share
3 answers

. N1570 Β§6.7.6.3p13 1 :

, , , , , .

, " " , const char *, - const char *, const char * const char Β§6.2.5p26

( ) , .

,

void foo (const int x);

void foo (int x) { ... }

void bar (const char *x)

void foo (char *x) { ... }

, , , . - , C ( , , ), , const T; T . , - , .


1 N1570 ISO C 2011 , .

, 1989 . Pre-C89 "K & R" C const, .

+6

C99 spec, 6.7.5.3.15 , :

, , (, ) , , , - . ( , , , , , .)

+2

cv- ( ) , . , , , . , .

, , , const, , , , . , , :

int foo(const int x);   // const on the parameter
int foo(int * const x);  // also const on the parater
int foo(const int *x);  // const in the type, not on the parameter
int foo(int const *x);  // also const in the type
0

All Articles