Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why declaring function parameter as "X* const"

Tags:

c++

Let's consider such application:

void foo (char* const constPointerToChar) {
    // compile-time error: you cannot assign to a variable that is const
    constPointerToChar = "foo";
}

int _tmain(int argc, _TCHAR* argv[])
{
    char* str = "hello";
    foo(str);
    printf(str);
    return 0;
}

Let's remove const keyword:

void foo (char* pointerToChar) {
    pointerToChar = "foo";
}

int _tmain(int argc, _TCHAR* argv[])
{
    char* str = "hello";
    foo(str);
    printf(str);
    return 0;
}

And output is hello. So even if function is allowed to change pointer it changes it's copy of pointer and original pointer was not changed.

This is expected because pointers are passed by value.

I do understand why things works this way but I do not understand why someone need to declare parameter as X* const.

When we declare function parameter as X* const we say that "Ok I promise inside my function i will not modify my own copy of your pointer." But why caller should care what happens with variables he never see and use?

Am I correct that declaring function parameter as X* const is useless?

like image 511
Oleg Vazhnev Avatar asked Dec 04 '25 16:12

Oleg Vazhnev


2 Answers

But why caller should care what happens with variables he never see and use?

He doesn't. In fact, you're allowed to leave that const out of declarations of the function, and only include it in the implementation.

Am I correct that declaring function parameter as X* const is useless?

No, it's as useful as declaring any other local variable const. Someone reading the function will know that the pointer value shouldn't change, which can make the logic a bit easier to follow; and no-one can accidentally break the logic by changing it when they shouldn't.

like image 81
Mike Seymour Avatar answered Dec 06 '25 05:12

Mike Seymour


The top level qualifier will be discarded in the function declaration (so it does not take part in the function signature) but will be enforced in the function definition.

There are some coding standards that suggest that you should take the value arguments as const (and return also const values), as to avoid potentially unwanted modifications of the arguments. I don't quite agree with that rationale, but there it is.

like image 33
David Rodríguez - dribeas Avatar answered Dec 06 '25 06:12

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!