Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const array const {}

Tags:

c

constants

c99

So you can do this:

void foo(const int * const pIntArray, const unsigned int size);

Which says that the pointer coming is read-only and the integer's it is pointing to are read-only.

You can access this inside the function like so:

blah = pIntArray[0]

You can also do the following declaration:

void foo(const int intArray[], const unsigned int size);

It is pretty much the same but you could do this:

intArray = &intArray[1];

Can I write:

void foo(const int const intArray[], const unsigned int size);

Is that correct?

like image 383
Matt Clarkson Avatar asked Aug 31 '11 16:08

Matt Clarkson


People also ask

What does const {} mean in JavaScript?

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

What does const {} mean in node JS?

Const is the variables declared with the keyword const that stores constant values. const declarations are block-scoped i.e. we can access const only within the block where it was declared. const cannot be updated or re-declared i.e. const will be the same within its block and cannot be re-declare or update.

What is a const array?

Arrays are Not Constants The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

Should array be const or let?

There is no preferred one, its based on your choice of usage for that array or object. You have to understand mutation and reassigning clearly. If your usecase only needs mutation, you can go for const.. if you need reassigning then go for let.


2 Answers

No, your last variant is not correct. What you are trying to do is achieved in C99 by the following new syntax

void foo(const int intArray[const], const unsigned int size);

which is equivalent to

void foo(const int *const intArray, const unsigned int size);

That [const] syntax is specific to C99. It is not valid in C89/90.

Keep in mind that some people consider top-level cv-qualifiers on function parameters "useless", since they qualify a copy of the actual argument. I don't consider them useless at all, but personally I don't encounter too many reasons to use them in real life.

like image 79
AnT Avatar answered Oct 14 '22 05:10

AnT


Use cdecl. It gives an error on the second entry. The first only clearly suggests that the second const refers to the *.

like image 25
Mihai Maruseac Avatar answered Oct 14 '22 03:10

Mihai Maruseac