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?
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.
The benefit of const correctness is that it prevents you from inadvertently modifying something you didn't expect would be modified.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
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.
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.
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