Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const parameter

Tags:

c++

constants

In C++, does the following make sense?

main()
{
 int a=10;
 fun(a);
}

void fun(const int a)
{
...
}

I can see a program similar to this compile but have linker issues. I just wanted to confirm if assigning a non const var to a const var is apt in C++.

like image 871
user844631 Avatar asked Feb 21 '26 09:02

user844631


2 Answers

Yes, it is OK.

a cannot be reassigned in fun(), exactly as if it would have been declared that way:

void fun(int param)
{
    const int a(param);

    ...

    a = 5; // this is illegal and won't compile.
}

As it is passed by copy, there is no impact on main()'s a anyway. Even if fun()'s a was declared as non-const and modified.

like image 162
Shlublu Avatar answered Feb 24 '26 00:02

Shlublu


In a function declaration the top level1 const is stripped out by the compiler, while it is kept in the definition.

The reason is that the top level element is copied, and from the point of view of the caller it does not really matter whether the copy is constant or not, so on that end const-ness is not an issue. On the other end, in the definition of the function the argument cont-ness is maintained as it can help the compiler detect unintended modifications of the argument inside the function.

So basically:

void foo( int );
void foo( const int );    // redeclaration of the same function
void foo( const int x ) {
   ++x;                   // error: x is const!!
}

In the code above there are two exactly equivalent declarations of foo (the compiler will remove the const from the declaration), and a single definition. Because the in the signature of foo in the definition x is declared as a constant integer, the compiler will complain if you try to increment it.

Some people will use the const in the definition to get the compiler to flag ++x as erroneous, but it is not common. On the other hand, whether the argument is declared as int or const int, for the caller they are the same.

1 Note that this only applies to the top level const, which is applicable to arguments passed by value and pointers, but never to references (a reference is always const: you cannot reassign the reference). So these are different function declarations:

void f( int& );
void f( int const & );
void f( int* );            // equivalent to void f( int * const )
void f( int const * );     // equivalent to void f( int const * const )
like image 35
David Rodríguez - dribeas Avatar answered Feb 23 '26 23:02

David Rodríguez - dribeas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!