
char^ to const char* casting
Quote:
>What I have looks like this:
>void function(char* variable)
>{
> const char* var = variable;
> function_that_needs_const_char(var);
> return;
>}
>Is this:
>a.) correct?
Yes, conversion from a pointer to a type to a to a pointer to a
more qualified version of that type is "safe" and supported in C
as an explicit conversion. Essentially a pointer to a const type
indicates that you won't modify what the pointer points to using that
pointer or a pointer derived from it.
Quote:
>b.) the best way to do this?
Since it is supported implicitly there is no need to use an extra
varaible just for the conversion:
void function(char* variable)
{
function_that_needs_const_char(variable);
return;
Quote:
}
You probably use this sort of thing all of the time without thinking
about it e.g.
printf("Some text\n");
A string literal has type array of char which gets converted to a
pointer to its first element (i.e. a char *) in a value context like this.
printf() requires a const char * as its first argument and the compiler
performs the conversion automatically. Other standard library functions
like strcmp(), fopen() also take const char * arguments and are happy
to take char *.
--
-----------------------------------------
-----------------------------------------