0

Trying to define a user-type I stumbled upon an error I don't quite understand: the following code works fine

const int a[5] = { 1, 2, 3, 4, 5 };

typedef const int costant;

costant b = 5;
costant *c = a;

void func( const int item )
{
    printf("Item: %i\n", item );
}

int main( void )
{
    func( a[0] );
    func( b );
    func( *c );
}

Nonethe less, initializing the pointer

costant *c = a[0];

fails stating that Initializer element is not costant. Trying to access the location a[0] to alter its content is refused with error assignment of read-only location.

Why is considered the array address a as const but not its element a[0], even though it is "read-only"?

Replacing the typedef with a #define costant const int doesn't change the behaviour.

1 Answers1

1

Unlike #define, which has the syntax #define NEW_SYMBOL [old_symbol], the syntax of typedef is:

typedef existing_type new_type;

So:

typedef const int constant;

Is valid C, whereas

typedef constant const int;

Is not.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85