Click here to Skip to main content
15,068,678 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hello,

I have a problem. I have to cast explicitly __FILE__ to signed char*.
I have a function call:

function(par1, par2, __FILE__)

__FILE__ is declared as const char*, but I need an explicit cast to convert __FILE__ to signed char* without a variable.

How can I do this?
Posted

There are two issues here: const versus non-const and char * versus signed char *.

__FILE__ is not a variable, it is a symbolic constant for a string literal. Trying to change what the char * points to at runtime is an error and should not be done.

If function() might change what is pointed to by its third parameter, then your only real alternatives are to not use function() here or to create a buffer variable and copy the string to it.

If function() is guaranteed to not make such a change - now or in a future reimplementation - than it "should" be revised so that its third parameter is a pointer to const. If this is not possible, you will have to cast away the constness. The C++-style cast for this is const_cast<>(), though by itself it will not deal with the char to signed char part of things.

Now, somewhat surprisingly, plain char, signed char, and unsigned char are officially not as related as you might expect. The meaning of casting between them is "unspecified" and can be implementation/platform dependent. (I need to figure this out better myself.) A C++ static_cast<>() is not legal for this.

If you meet the conditions where you can do this, your options are:

(signed char*)__FILE__

or

reinterpret_cast<signed char*>( const_cast<char *>( __FILE__ ) )
   
v2
I'm not sure I understand the whys and wherefores but this should work:
function(par1, par2, (signed char*)__FILE__);
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900