+ 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 ?
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).
+ 2
I don't think there's any use for doing that and some compilers even issue warnings against it
[-Wignored-qualifiers]
+ 1
Thank you Arsenic ... Perfect use of the const value return type.....
But does any one do something like a+b = c ?
+ 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.