Yes, char *input
can be assigned to a variable of type const char *
, with an implicit type conversion, and C arguments work as if by assignment. The rule is this in C11 6.5.16.1.1:
6.5.16.1 Simple assignment
Constraints
- One of the following shall hold:
[...]
- the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
[...]
In doing
const char *cinput;
cinput = input;
the left operand cinput
has unqualified pointer type (the pointer type itself is not const
-qualified); and so does the right operand.
The left operand is a pointer to a const-qualified type (const char
), and the type pointed to by right operand does not have any qualifiers. The type pointed to by the left has therefore all qualifiers of the type pointed to by the right and additional const
qualifier, hence the assignment is valid.
And in calling a function
double str2double(const char* input);
[...]
char *foo = ...
str2double(foo);
the behaviour is as if the value of foo
was assigned to the input
parameter by a simple assignment.
A string literal in C is of type an array of unqualified char, which decays to char *
, i.e. if it were not OK to pass char *
into such a function, you could not use double str2double( const char* input);
passing a string literal as the argument.