I mean it ensures that I can't change the value of i
Yes, that is what it does.
but I mean it's kinda useless isn't it?
In this example it's not useful, but imagine that your function was 300 lines long instead of 1 line long, and was being maintained over several years by multiple different programmers of varying skill levels.
When looking at code in the middle of a big function like that, it's often very useful to know what the value of i
will be on a given line. If i
has been marked as const
, then it's easy to know that the value of i
is guaranteed to be equal to the value that was passed in to the function, because the compiler (more-or-less) guarantees that to you; if any of the code earlier in the function had tried to assign a different value to i
, the function would not have compiled. Without the const
tag, on the other hand, you'll have to manually read through all the code earlier in the function to verify "by eye" that none of that code assigned a different value to i
, or if it did, under what circumstances that might occur and what new value it might assign. That's a lot of extra programmer-time, and assignments like that might be very easy to miss.
Hence, the const
tag can be a real time-saver for programmers, in some cases.
A second benefit is that with the const
tag you can call the function with a temporary-value as an argument, like this:
square(9)
... whereas without the const
the above would be a compile-time error. (In this case you could get also around that error by changing the argument type to a simple int
or const int
instead of an int &
, but in general you often want to pass by-reference to avoid unnecessary copying of objects during function-calls)