Use of 'const' for function parameters

How much do you select const? Do you simply make features const when essential or do you go the entire hog and also utilize it almost everywhere? As an example, visualize a straightforward mutator that takes a solitary boolean parameter:

void SetValue(const bool b) { my_val_ = b; }

Is that const in fact valuable? Directly I decide to utilize it thoroughly, consisting of parameters, yet in this instance I ask yourself if it is rewarding?

I was additionally stunned to find out that you can leave out const from parameters in a function declaration yet can include it in the function definition, for example:

. h documents

void func(int n, long l);

. cpp documents

void func(const int n, const long l)

Is there a factor for this? It appears a little uncommon to me.

2022-07-11 20:36:59
Source Share
Answers: 21

As parameters are being gone by value, it does not make any kind of distinction if you define const or otherwise from the calling function is perspective.It primarily does not make any kind of feeling to proclaim go by value parameters as const.

2022-07-13 02:41:20

const should have been the default in C++. Like this :

int i = 5 ; // i is a constant

var int i = 5 ; // i is a real variable
2022-07-12 13:23:50

I do not make use of const for value - passed parametere. The customer does not care whether you change the parameter or otherwise, it is an execution information.

What is actually vital is to note approaches as const if they do not change their instance. Do this as you go, due to the fact that or else you could wind up with either great deals of const_cast<> or you could locate that noting a method const calls for transforming a great deal of code due to the fact that it calls various other approaches which need to have been significant const.

I additionally often tend to note neighborhood vars const if I do not require to change them. I think it makes the code less complicated to recognize by making it less complicated to recognize the "moving parts".

2022-07-12 10:25:56

Const parameter serves just when the parameter is gone by reference i.e., either reference or reminder. When compiler sees a const parameter, it see to it that the variable made use of in the parameter is not changed within the body of the function. Why would certainly any person intend to make a by - value parameter as constant?: -)

2022-07-12 10:25:26

If the parameter is gone by value (and also is not a reference), generally there is very little distinction whether the parameter is proclaimed as const or otherwise (unless it has a reference participant - - not a trouble for constructed - in kinds). If the parameter is a reference or reminder, it is generally far better to shield the referenced/pointed - to memory, not the reminder itself (I assume you can not make the reference itself const, not that it matters high as you can not transform the umpire). It appears an excellent suggestion to shield every little thing you can as const. You can omit it without anxiety of slipping up if the parameters are simply PODs (consisting of constructed - in kinds) and also there is no opportunity of them transforming better along the roadway (as an example in your instance the bool parameter).

I really did not find out about the.h/. cpp documents declaration distinction, yet it does make some feeling. At the equipment code degree, absolutely nothing is "const", so if you proclaim a function (in the.h) as non - const, the code coincides as if you proclaim it as const (optimizations apart). Nonetheless, it aids you to get the compiler that you will certainly not transform the value of the variable inside the execution of the function (. ccp). It could come convenient in case when you are acquiring from a user interface that permits adjustment, yet you do not require to transform to parameter to attain the called for capability.

2022-07-12 10:25:23

I often tend to make use of const any place feasible. (Or various other ideal search phrase for the target language.) I do this totally due to the fact that it permits the compiler to make added optimizations that it would certainly not have the ability to make or else. Given that I have no suggestion what these optimizations might be, I constantly do it, also where it appears silly.

For all I recognize, the compiler could quite possibly see a const value parameter, and also claim, "Hey, this function isn't changing it anyhow, so I can go by reference and also conserve some clock cycles." I do not assume it ever before would certainly do something, given that it transforms the function trademark, yet it makes the factor. Possibly it does some various pile adjustment or something The factor is, I do not recognize, yet I do recognize attempting to be smarter than the compiler just brings about me being reproached.

C+npls has some added luggage, with the suggestion of const - accuracy, so it comes to be a lot more vital.

2022-07-12 10:23:41

The adhering to 2 lines are functionally equivalent:

int foo (int a);
int foo (const int a);

Obviously you will not have the ability to change a in the body of foo if it is specified the 2nd means, yet there is no distinction from the exterior.

Where const actually can be found in convenient is with reference or reminder parameters:

int foo (const BigStruct &a);
int foo (const BigStruct *a);

What this claims is that foo can take a huge parameter, probably a data structure that is gigabytes in dimension, without replicating it. Additionally, it claims to the customer, "Foo will not * transform the materials of that parameter." Passing a const reference additionally permits the compiler to ensure efficiency choices.

*: Unless it casts away the const - ness, yet that is an additional blog post.

2022-07-12 10:23:28

In the instance you state, it does not influence customers of your API, which is why it is not generally done (and also isn't essential in the header). It just influences the execution of your function.

It is not specifically a negative point to do, yet the advantages aren't that wonderful considered that it does not influence your API, and also it includes keying, so it is not generally done.

2022-07-12 10:05:01

I would not place const on parameters like that - every person currently recognizes that a boolean (in contrast to a boolean&) is constant, so including it in will certainly make individuals assume "wait, what?" or perhaps that you are passing the parameter by reference.

2022-07-12 10:04:54

things to bear in mind with const is that it is a lot easier to make points const from the beginning, than it is to attempt and also place them in later on.

Usage const when you desire something to be unmodified - its an included tip that defines what your function does and also what to anticipate. I've seen several an C API that want several of them, specifically ones that approve c - strings!

I would certainly be extra likely to leave out the const search phrase in the cpp documents than the header, yet as I often tend to reduce+paste them, they would certainly be maintained in both areas. I have no suggestion why the compiler permits that, I presume its a compiler point. Ideal technique is most definitely to place your const search phrase in both documents.

2022-07-12 10:04:48

Ah, a challenging one. On one side, a declaration is a contract and also it actually does not make good sense to pass a const argument by value. On the various other hand, if you consider the function execution, you offer the compiler extra opportunities to maximize if you proclaim an argument constant.

2022-07-12 10:04:45

There is actually no factor to make a value - parameter "const" as the function can just change a duplicate of the variable anyhow.

The factor to make use of "const" is if you are passing something larger (as an example a struct with great deals of participants) by reference, in which instance it makes certain that the function can not change it ; or instead, the compiler will certainly whine if you attempt to change it in the standard means. It stops it from being mistakenly changed.

2022-07-12 10:04:30

I make use of const on function parameters that are referrals (or reminders) which are just [in] information and also will certainly not be changed by the function. Definition, when the objective of making use of a reference is to stay clear of duplicating information and also not to permit transforming the passed parameter.

Placing const on the boolean b parameter in your instance just places a restraint on the execution and also does not add for the class is user interface (although not transforming parameters is generally suggested).

The function trademark for

void foo(int a);

and also

void foo(const int a);

coincides, which clarifies your.c and.h


2022-07-12 10:03:56

All the consts in your instances have no objective. C+npls is pass - by - value by default, so the function obtains duplicates of those ints and also booleans. Also if the function does change them, the customer is duplicate is not influenced.

So I would certainly stay clear of added consts due to the fact that

  • They are redudant
  • They mess up the message
  • They stop me from transforming the come on value in instances where it could be valuable or reliable
2022-07-12 10:03:44

I make use of const were I can. Const for parameters suggests that they need to not transform their value. This is specifically beneficial when going by reference. const for function proclaims that the function needs to not transform the courses participants.

2022-07-12 10:02:56

The factor is that const for the parameter just uses in your area within the function, given that it is working with a duplicate of the information. This suggests the function trademark is actually the very same anyways. It is possibly negative design to do this a whole lot though.

I directly often tend to not make use of const with the exception of reference and also reminder parameters. For replicated things it does not actually issue, although it can be more secure as it signifies intent within the function. It is actually a reasoning call. I do often tend to make use of const_iterator though when knotting on something and also I do not plan on changing it, so I presume per his very own, as long as const accuracy for reference kinds is carefully kept.

2022-07-12 10:01:48

When I coded C+npls for a living I consted every little thing I perhaps could. Making use of const is a wonderful means to aid the compiler aid you. As an example, const - ing your method return values can conserve you from typos such as:

foo() = 42

when you meant:

foo() == 42

If foo() is specified to return a non - const reference:

int& foo() { /* ... */ }

The compiler will gladly allow you assign a value to the confidential short-lived returned by the function call. Making it const:

const int& foo() { /* ... */ }

Eliminates this opportunity.

2022-07-12 09:26:19

Sometimes (frequently!) I need to disentangle somebody else is C+npls code. And also most of us recognize that somebody else is C+npls code is a full mess virtually necessarily So the first point I do to decode neighborhood information circulation is placed const in every variable definition till compiler begins barking. This suggests const - certifying value debates too, due to the fact that they are simply expensive neighborhood variables booted up by customer.

Ah, I desire variables were const by default and also mutable was needed for non - const variables

2022-07-12 09:26:04

const is meaningless when the argument is gone by value given that you will certainly not be changing the customer is object.

const needs to be favored when going by reference, unless the objective of the function is to change the passed value.

Ultimately, a function which does not change existing object (this) can, and also possibly need to be proclaimed const. An instance is below:

int SomeClass::GetValue() const {return m_internalValue;}

This is an assurance to not change the challenge which this call is used. To put it simply, you can call:

const SomeClass* pSomeClass;

If the function was not const, this would certainly cause a compiler caution.

2022-07-12 09:19:31

const is meaningless when the argument is gone by value given that you will certainly not be changing the customer is object.


It has to do with self - recording your code and also your presumptions.

If your code has many individuals working with it and also your features are non - unimportant after that you need to note const any kind of and also every little thing that you can. When creating commercial - toughness code, you need to constantly think that your colleagues are psychotics attempting to get you any kind of means they can (specifically given that it is usually on your own in the future).

Besides, as someone stated previously, it could aid the compiler maximize points a little bit (though it is a slim chance).

2022-07-12 09:14:11

Marking value parameters 'const' is most definitely a subjective point.

Nonetheless I in fact favor to mark value parameters const, similar to in your instance.

void func(const int n, const long l) { /* ... */ }

The value to me remains in plainly showing that the function parameter values are never ever transformed by the function. They will certainly have the very same value at the start as at the end. For me, it becomes part of maintaining to a really useful shows type of design.

For a brief function, it is perhaps a waste of time/space to have the 'const' there, given that it is generally rather noticeable that the debates aren't changed by the function.

Nonetheless for a bigger function, its a kind of execution documents, and also it is applied by the compiler.

I can be certain if I make some calculation with 'n' and also 'l', I can refactor/move that calculation without anxiety of obtaining a various outcome due to the fact that I missed out on an area where one or both is transformed.

Given that it is an execution information, you do not require to proclaim the value parameters const in the header, similar to you do not require to proclaim the function parameters with the very same names as the execution makes use of.

2022-07-12 08:43:46