Using 'const' in C, what kind of wrapping problems might arise?

I would like to use 'const' in C interface functions to note that some char * arguments are not modified by the function.

What can prevent porting this code to different platforms? Is "const" support in C code pretty standard? When did it officially become standard C?

+3
source share
6 answers

I can not imagine what is constnot supported by any compilers, so the transfer should be non-emission. If you found such a beast, you could just put

#define const

- , const . ( ).

+5

. , C89.

+3

MSVC, C.

+3

const. . C89, IIRC.

+1

, const . , , - . const . , :

. wikipedia const-correctness:

. - const const ( ). const , , , , ( "pointee" ). , . , const , , - . - const . :

void Foo( int       *       ptr,
      int const *       ptrToConst,
      int       * const constPtr,
      int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the pointee
ptr  = 0; // OK: modifies the pointer

*ptrToConst = 0; // Error! Cannot modify the pointee
ptrToConst  = 0; // OK: modifies the pointer

*constPtr = 0; // OK: modifies the pointee
constPtr  = 0; // Error! Cannot modify the pointer

*constPtrToConst = 0; // Error! Cannot modify the pointee
constPtrToConst  = 0; // Error! Cannot modify the pointer
}
+1

const, .

(WG14/N1336 6.7.3, 117)

(-) ; , , , (EEPROM Flash).

, * const * .

:

void foo(const char* arg); /* intent is not to modify anything through arg, but arg refers to a memory location in ROM */
/* ... */
char bar[] = "abc";
const char baz[] = "def";
foo(bar);  /* behavior is undefined! */
foo(baz);  /* should be ok */

, , - . FatFs ImageCraft PSoC1 #define consts, .

+1

All Articles