How far should I put the const of the function parameter?

Asked 1 years ago, Updated 1 years ago, 129 views

How much const should I write? Should I use all the variables that don't change? Even on a single line of code?

void printValue(const bool b) { cout << b << endl; }

Does writing like this really help? I usually use const a lot, but why do I use this these days? That's what I think

And out of the codes that other people made (like the source code below), Do not use const in the function declaration There are some const written only in the definition, why are you doing this?

/*   .h file    */
void func(int n, long l);


/*   /*   .cpp file    */
void func(const int n, const long l)

c++ const

2022-09-22 22:29

1 Answers

There is no const in the declaration, but const is used only in the definition because This is because const parameter is written as const only within that function.

That is,


void myPrint(const int a){
    cout << a << endl;
}

...

int val = 5;
myPrint(val)

In the same code as above, val is not const, but only a that copies the value of val is constconst and it doesn't play such a big role without it.

But it's not a good code, so it's better not to use it.

In my case, const is not often attached unless it is an iterator of a reference, pointer, or repetitive statement. call by value only copies the value and retains the original. const is a safer and more certain way, If it's a code you use alone, I think it's better to use it comfortably.

If you work with multiple people, make sure to put const. !!!Don't trust your colleagues!!!


2022-09-22 22:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.