Quick question:
int testfunc1 (const int a)
{
return a;
}
int testfunc2 (int const a)
{
return a;
}
Are these two functions the same in every aspect or is there a difference? I'm interested in an answer for the C-language, but if there is something interesting in the C++ language, I'd like to know as well.
I think in this case they are the same, but here is an example where order matters:
Yes, they are same for just
int
and different for
int*
const T
andT const
are identical. With pointer types it becomes more complicated:const char*
is a pointer to a constantchar
char const*
is a pointer to a constantchar
char* const
is a constant pointer to a (mutable)char
In other words, (1) and (2) are identical. The only way of making the pointer (rather than the pointee)
const
is to use a suffix-const
.This is why many people prefer to always put
const
to the right side of the type (“East const” style): it makes its location relative to the type consistent and easy to remember (it also anecdotally seems to make it easier to teach to beginners).There is no difference. They both declare "a" to be an integer that cannot be changed.
The place where differences start to appear is when you use pointers.
Both of these:
declare "a" to be a pointer to an integer that doesn't change. "a" can be assigned to, but "*a" cannot.
declares "a" to be a constant pointer to an integer. "*a" can be assigned to, but "a" cannot.
declares "a" to be a constant pointer to a constant integer. Neither "a" nor "*a" can be assigned to.
const int
is identical toint const
, as is true with all scalar types in C. In general, declaring a scalar function parameter asconst
is not needed, since C's call-by-value semantics mean that any changes to the variable are local to its enclosing function.Prakash is correct that the declarations are the same, although a little more explanation of the pointer case might be in order.
"const int* p" is a pointer to an int that does not allow the int to be changed through that pointer. "int* const p" is a pointer to an int that cannot be changed to point to another int.
See http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5.