Home > front end >  Can an array-parameter be declared Constant?
Can an array-parameter be declared Constant?

Time:11-09

If I declare a function parameter using array notation (eg: int a[]), is there a way to make that pointer constant, so that it cannot be assigned to?

I am referring to the base of the array (eg. the name), and not the data within the array, which can still be non-const.

Please see the comments in the code below.

void foo(int *const array) // Array is declared as a Constant Pointer
{
    static int temp[] = { 1, 2, 3 };
    array = temp; // This assignment does not Compile, because array is a Constant Pointer, and cannot be assigned.
                  // This is the behavior I want: a Compile Error, to prevent errant assignments.
}

// Array is declared with array[] notation.
// It will decay to a non-const pointer.
// I want it to decay to a const-pointer.
void bar(int array[])
{
    static int temp[] = { 1, 2, 3 };
    array = temp;
    // This assignment compiles as valid code, because array has decayed into a non-const pointer.
    // Is there a way to declare parameter array to be a Constant Pointer?
}

I'm looking for a way to prevent function bar from compiling, while still using the [] notation in the parameter list.

CodePudding user response:

You can add the const qualifier inside the brackets. That will apply it to the parameter itself.

void bar(int array[const]) 

This is exactly equivalent to your first declaration:

void foo(int *const array)

As spelled out in section 6.7.6.3p7 of the C standard regarding function declarators:

A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.

  • Related