简体   繁体   中英

Can I pass char* to const char* in C?

I am implementing a function that converts string into double in C. The function is not destructive, ie I do not modify the string passed and I just read it in the function. I want to pass char*, const char*, and also string literal to the function.

Is the following function appropriate for this purpose? I think the question comes down to whether passing char* to const char* is defined and allowed in C.

double str2double( const char* input);

Thank you. (I've found some similar question title, but their answers are vague for me, and I am asking here.)

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

  1. 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 * , ie 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.

Yes it is allowed. Using const in this case is good practice. By adding it to the function arguments you promise not to modify the data located at input .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM