Because the practice of "constant parameter" only exists in C

9

In C, there is the practice of applying the modifier "const" to function parameters when the function is not intended to change the parameter. As in this code:

char process_string(const char *str);

Because in other languages there is no such practice? Because it's not common to see something like this:

public String processString(final String str);
    
asked by anonymous 13.03.2014 / 08:04

1 answer

10

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