I am a novice programmer exploring the depths of C. Why does some inbuilt functions return a const value ? Can somebody explain the benefits or drawbacks of using const in method returns ?
-
Java and C are very different languages following very different language philosophies. Java's `final` is used very differently C's `const`, and it's probably dangerous to compare the two as a novice. – PC Luddite Jul 02 '15 at 19:17
-
I don't think this is a duplicate. While the OP incorrectly conflates `const` and `final`, the question is asking about their difference and I think the answers are important because they show how the OP is incorrect. I think this is useful for people who may have made the same mistake. The linked question only talks about `const` in C. – Vivin Paliath Jul 07 '15 at 19:51
2 Answers
Using final and const in returning values from functions and methods is to keep people from changing their values. For example, if i had (in c)
char* getChar()
{
return "string";
}
and I didn't want someone to use it like
char myChar = getChar()[0]++;
then i would have to return a const, to keep it from being changed.
For Java, it's very different. You don't return final values, you make methods final.
final
is used with a Java method to mark that the method can't be overridden (for object scope) or hidden (for static). This allows the original developer to create functionality that he can be sure will not be changed by others, and that is all the guarantee it provides.

- 1,778
- 8
- 15
-
-
@DJClayworth yup! But OP was just asking about method/function returns i believe. – Olivier Poulin Jul 02 '15 at 19:35
-
In that C example, you'd still be returning a non-const value, it's just that that value would be a pointer to a const char. – Oliver Charlesworth Jul 09 '15 at 06:34
C's const
and Java's final
are very different, and especially in the case you're talking about.
In C (disclaimer: I haven't done C in a while so please let me know where I'm wrong) let's look at this example:
const int something() {
return 3;
}
The const
is meaningless because it's not like you can do:
something() = 3;
For some more information on const
return values in C, take a look at the following:
const
makes no sense for return values...- Purpose of returning by const value (this is C++, but still useful).
In Java, I'm assuming you're talking about something like:
public final int something() {
...
}
Here final
has nothing to do with the return value. final
here means that if you extend the class that something()
belongs to, you cannot override the implementation of something()
. This is somewhat similar in spirit to final
variables; these are variables whose values you cannot change once they are set.

- 1
- 1

- 94,126
- 40
- 223
- 295