Keil Logo


In ANSI C, the const type qualifier is used to define and access objects that are constant and that may not be changed. A variable that is declared with const may not be assigned to in the program.

The Cx51 Compiler conforms to the ANSI definition of const objects.

  • Variables declared with the const type qualifier alone are stored in the memory area (data, idata, xdata, and so on) associated with their definition.
  • Variables you want to locate in ROM must be declared with the code memory type. For example:
    code char test[] = "This is a text string";
  • Variables declared with const far are stored in the HCONST memory area. This area is typically allocated to ROM memory.
  • Finally, the STRING compiler directive specifies where string constants are stored. This directive allows you to place strings in CODE memory, HCONST memory, or in XCONST memory (constant space in XDATA).

Constant objects are typically initialized when they are defined (in your source files). The following variable definitions show different ways to create constant objects:


/* table is stored in the default memory area */
const int table[2][2] =
  { 0, 2, 4, 8 };

/* pi is stored in the HCONST class */
const float far pi = 3.1415927;

/* The string is stored in the XCONST class */
printf("This is a string\n");

When using pointers to const objects, you may exclude the const type qualifier in the pointer definition. For example:

const unsigned char mask [] =
  { 0x01, 0x02, 0x04, 0x08 };

const unsigned char *cp = mask;
      unsigned char  *p = mask;  /* same as cp */


*p = 'a';    // This has no effec.
             // It causes no error or warning

*cp = 'a';   // This causes an error

As shown, it is possible to assign the address of a const object (mask) to a non-const pointer (p) and subsequently use the pointer to change the const object. In this case, the compiler does generate code to write to the const object. The effects of this code is undefined and may or may not work as expected.

It is not possible to use a const pointer to change the const object it points to. Attempts to do so will cause a compiler error.

An interesting use of const is to define a pointer that may not be changed. For example:

char text [] = "This is a string.";
char *const textp = text;
*textp = 'A';    // This is OK (it changes text[0])
textp++;         // This causes an error (textp is const)
textp[2] = 'B';  // This is OK (it changes text[2])
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.