Jak se projevuje 'const'

19. prosinec 2010
Označeno jako: C, programování, const.

Toto je testovací kód, který se pochopitelně nezkompiluje, a i kdyby, nic rozumného dělat nebude. Stejně jako strcpy se chová i free.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
  const char *       str1 = (char*) malloc(10*sizeof(char));
  char * const       str2 = (char*) malloc(10*sizeof(char));
  const char * const str3 = (char*) malloc(10*sizeof(char));

  str1 = NULL;
  str2 = NULL;
  str3 = NULL;

  strcpy(str1, "a");
  strcpy(str2, "a");
  strcpy(str3, "a");

  return 0;
}

Jak to vidí GCC 4.4.5

x = NULL strcpy(x, "a")
const char * OK error: invalid conversion from 'const char' to 'char'
char * const error: assignment to read-only variable OK
const char * const error: assignment to read-only variable error: invalid conversion from 'const char' to 'char'

Jak to vidí CLang 1.1

x = NULL strcpy(x, "a")
const char * OK
error: no matching function for call to 'strcpy'
note: candidate function not viable: 1st argument
('char const *const') would lose const qualifier
char * const error: read-only variable is not assignable OK
const char * const error: read-only variable is not assignable
error: no matching function for call to 'strcpy'
note: candidate function not viable: 1st argument
('char const *const') would lose const qualifier