First of all, the codes you posted are not equivalent: in the first case, the str
pointer can be reassigned at will, but the content of the specified string no (more details in that question in SOEN ). In the second, the reference str
can not be modified, but the contents of the object could at first be - if String
was not immutable (I'm thinking of Java, but if you were referring to another language please specify) / p>
This example in ideone shows this clearly:
char *process_string(const char *str) {
str = outra_string; // Pode mudar o ponteiro à vontade
//str[0] = '1'; // Não pode mexer no conteúdo
return str;
}
char *process_string_2(char * const str) {
//str = outra_string; // Não pode mudar o ponteiro
str[0] = '2'; // Pode mexer no conteúdo à vontade
return str;
}
Why is this not common in other languages? Unfortunately I can not say ... It would be extremely useful if a compiler would guarantee the contract that "this method has no side effects [in this parameter at least]" but I have no idea how difficult it is to implement (in particular object oriented languages, which do not support pointer arithmetic and make extensive use of references).
And speaking of references, the main reason why you do not see many final
parameters is that it is common for references to objects to be by value . That is, the object is not copied, but the reference to it is yes. So, what harm does it have to reassign its own parameters? Only she sees them really ... And for that very reason it is difficult to see a function in C with parameters like the process_string_2
of the above example.
The only case I know of that a final
parameter may be required is when it is used in a
13.03.2014 / 09:23