Alex Rivera | Logout

Adding const keyword to an array passed as a parameter to function

Asked 2012-06-06T20:14:37.430
20

Is there any way that I can add const keyword to an array passed as a parameter to function:

void foo(char arr_arg[])

If I place const before char (void foo(const char arr_arg[])) or after char(void foo(char const arr_arg[])), that would mean than it's char which is constant, not the arr_arg.

I have just read that under the hood an array sent as a parameter to function is represented as a pointer, so void foo(char arr_arg[]) is the same as void foo(char* ptr_arg). Taking it into account, I may rewrite the function as void foo(char * const ptr_arg) for it to be exactly what I want to achieve.

But I want to know if there is a way to add const keyword in this declaration void foo(char arr_arg[]) for it to be the same as void foo(char * const ptr_arg) (and not void foo(char const * ptr_arg) or void foo(const char * ptr_arg))?

I just want to understand if there is a syntax to make arr_arg constant with array notation [].

Edit
Report

1 Answer

2

Yes, in C this is possible since C99:

void foo(char ptr_arg[const]);

is valid syntax and equivalent to

void foo(char *const ptr_arg);

More generally the [] may contain any type qualifier, static and an integer expression. But

The optional type qualifiers and the keyword static shall appear only in a declaration of a function parameter with an array type, and then only in the outermost array type derivation.

that is for the dimension that is equivalent to the pointer declaration.

answered 2012-06-06T20:29:11.753

Your Answer