How do I convert a char
to an int
in C and C++?
Presumably you want this conversion for using functions from the C standard library.
In that case, do (C++ syntax)
typedef unsigned char UChar;
char myCppFunc( char c )
{
return char( someCFunc( UChar( c ) ) );
}
The expression UChar( c )
converts to unsigned char
in order to get rid of negative values, which, except for EOF, are not supported by the C functions.
Then the result of that expression is used as actual argument for an int
formal argument. Where you get automatic promotion to int
. You can alternatively write that last step explicitly, like int( UChar( c ) )
, but personally I find that too verbose.
Cheers & hth.,