I am new to C so I hope I am using the right terminology. I have seen a number of resources suggesting that one should use VLA syntax for function parameters that should be non-null pointers like so
void foo(char bar[static 1])
meaning bar
should be a non-null pointer to a char because pointer decay. Some compilers might emit a warning about passing a null-pointer.
I am wondering how I would then declare the parameter as a const
pointer to a const
char. So what would be the VLA syntax equivalent of
void foo(char bar* const)
This works for pointer to const char
void foo(const char bar[static 1])
but
void foo(const char const bar[static 1])
emits a warning about duplicate const
.
You need to put the const
keyword inside of the square brackets:
void foo(const char bar[static const 1])
This is (more or less) equivalent to:
void foo(const char * const bar)
void foo(const char bar[static const 1])
is equivalent to:
void foo(const char*const bar)
(apart from the potential null pointer check)
That is, qualifiers for the pointed-at type are written as usual to the left of the pointed-at type specifier: const char
.
Whereas all qualifiers present between [ ]
are applied to the "decayed" pointer type itself. The easiest way to understand it might be to consider which pointer type that's equivalent to the array parameter version. In this case void foo(const char bar[1])
is 100% equivalent to void foo(const char* bar)
, the former gets adjusted to the latter.
void foo(const char bar[static const 1])
^-------------- all type qualifiers from here
void foo(const char*const bar)
^------------------ end up here when the array parameter gets adjusted
This is important to know for the rare case when you are dealing with restrict
pointers. If you have two arrays which are guaranteed not to overlap and can't be null pointers, then:
void foo (char a1[restrict static 1], char a2[restrict static 1])
// gets adjusted to:
void foo (char*restrict a1, char*restrict a2)
Similarly for 2D arrays:
void foo (size_t n, char bar[const][n]);
->
void foo (size_t n, char(*const bar)[n]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With