+ 2

What is use of const int from a method

Hi What is use of const int add(int a , int b) { return a+b; } I can understand member method as const , but what is importance of returning const int? What can I do with const int as sum ?

7th May 2021, 8:57 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Respostas
+ 1
You will see no problem till the time you are dealing with in-build data types. You will see it's importance when dealing with user defined data types, where making return type of a function const makes it impossible to be used as an lvalue, this is used a lot especially when overloading operators of classes so that stuff like (a + b) = c doesn't compile and get noticed by program at compile-time only. You can see an example of this here 👇 https://code.sololearn.com/cejBjuUiFhxj/?ref=app You can't see any effect in primitive types because the compiler already prevents it from being an lvalue (because it’s always a value, and not a variable).
7th May 2021, 1:17 PM
Arsenic
Arsenic - avatar
+ 2
I don't think there's any use for doing that and some compilers even issue warnings against it [-Wignored-qualifiers]
7th May 2021, 10:58 AM
Anthony Maina
Anthony Maina - avatar
+ 1
Thank you Arsenic ... Perfect use of the const value return type..... But does any one do something like a+b = c ?
8th May 2021, 4:07 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta well, I personally haven't seen anyone doing it till now, but it's better to not let compiler compile this madness than confusing everyone else later.
8th May 2021, 4:35 PM
Arsenic
Arsenic - avatar