LunchMarble
LunchMarble

Reputation: 5141

How do I pass an entire array pointer as const such that the values cannot be changed? C++

How do I pass an entire array pointer as const such that the values cannot be changed? I am passing in an array to a function like this:

double myArr[] { 1, 2, 3, 4, 5 };
double* pArr = myArr;

double myVal = MyFunc(pArr, 5);

MyFunc's header right now is:

MyFunc(double* pArr, int length)

I want to make sure that the function cannot modify the values inside the array at all.

How do I do this?

Upvotes: 2

Views: 149

Answers (5)

Bo Persson
Bo Persson

Reputation: 92261

How do I pass an entire array pointer as const?

Just do it!

MyFunc(const double* pArr, int length)

Upvotes: 2

iammilind
iammilind

Reputation: 69988

You can pass it by const pointer,

MyFunc(const double* const pArr, int length); // pArr or content of pArr will not change

If you have liberty to pass myArr then pass it by reference:

MyFunc(const double (&arr)[length]); // where length is known at compile time

Upvotes: 3

Cameron
Cameron

Reputation: 98746

Change your function signature to:

MyFunc(double const* pArr, int length);

Note that this is equivalent to:

MyFunc(const double* pArr, int length)

Which one you prefer is a matter of pure taste (I prefer the first, as I find it more readable -- it's the items in pArr that are const, not the pointer itself).

Upvotes: 7

Chad
Chad

Reputation: 19032

Pass the argment as const pointer. The function signature will look like this:

double MyFunc(const double* arr, size_t count);

Upvotes: 2

bdonlan
bdonlan

Reputation: 231143

Just make MyFunc take (const double *pArr, int length) for its arguments.

Upvotes: 3

Related Questions