jt27
jt27

Reputation: 53

What is the difference between int const function(parameters), int function(const parameters), and int function(parameters) const?

I'm working on an assignment for my CS class and it uses const, and I am kind of confused as to when to use each.

What are the differences between these 3 functions?

 int const function(parameters)
 int function(const parameters)
 int function(parameters) const

Thanks in advance!

Upvotes: 4

Views: 4060

Answers (2)

Saif
Saif

Reputation: 7052

Considering you talking about c++:

const int function(parameters) // instead of your  int const function(parameters)

will return a constant to the int

int function(const parameters)

The parameters will be considered as constant inside the method, which means they will not be changed.

int function(parameters) const

This function will not change any class variable (if the member is not mutable)

Upvotes: 2

Paul R
Paul R

Reputation: 213080

int const function(parameters)

The const is redundant. Declaring a simple type such as int as a const return value is not useful, although it may help to make the code more self-documenting. If the return type is a reference or pointer however then the story changes.

int function(const parameters)

The parameters passed to function are const and so can not be modified.

int function(parameters) const

function is a method which does not modify any of the member variables in the object instance for which it is being invoked.

Upvotes: 4

Related Questions