Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Const correctness and pointer arguments

Tags:

I understand that a const pointer can be declared a couple ways:

const int * intPtr1; // Declares a pointer that cannot be changed. int * const intPtr2; // Declares a pointer whose contents cannot be changed.  // EDIT: THE ABOVE CLAIMS ARE INCORRECT, PLEASE READ THE ANSWERS. 

But what about the same principles within the context of function arguments?

I would assume that the following is redundant:

void someFunc1(const int * arg); void someFunc2(int * arg); 

Since someFunc 1 and 2 do a pass-by-value for the pointer itself, its impossible for someFunc1 to change the value of the original pointer, in a given call to the function. To illustrate:

int i = 5; int * iPtr = &i;  someFunc1(iPtr); // The value of iPtr is copied in and thus cannot be changed by someFunc1. 

If these are true, then there is no point in ever declaring a function with a 'const int * ptr' type arg, correct?

like image 337
Ben Avatar asked Jan 10 '12 18:01

Ben


People also ask

Does C have const correctness?

In C, C++, and D, all data types, including those defined by the user, can be declared const , and const-correctness dictates that all variables or objects should be declared as such unless they need to be modified.

Why is const correctness important?

The benefit of const correctness is that it prevents you from inadvertently modifying something you didn't expect would be modified.

What does const& mean in C++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.

Can pointer change const value?

const int * is a pointer to an integer constant. That means, the integer value that it is pointing at cannot be changed using that pointer.


1 Answers

You have it backwards:

const int * intPtr1; // Declares a pointer whose contents cannot be changed. int * const intPtr2; // Declares a pointer that cannot be changed. 

The following const is indeed unnecessary, and there's no reason to put it in a function declaration:

void someFunc1(int * const arg); 

However, you might want to put it in the function implementation, for the same reason that you might want to declare a local variable (or anything else) const - the implementation may be easier to follow when you know that certain things won't change. You can do that whether or not it's declared const in any other declarations of the function.

like image 120
Mike Seymour Avatar answered Nov 22 '22 11:11

Mike Seymour