简体   繁体   中英

Is unsigned char('0') legal C++

The following compiles in Visual Studio but fails to compile under g++.

int main()
{
    int a = unsigned char('0');
    return 0;
}

Is unsigned char() a valid way to cast in C++?

No, it's not legal.

A function-style explicit type conversion requires a simple-type-specifier , followed by a parenthesized expression-list . (§5.2.3) unsigned char is not a simple-type-specifier ; this is related to a question brought up by James .

Obviously, if unsigned char was a simple-type-specifier , it would be legal. A work-around is to use std::identity :

template <typename T>
struct identity
{
    typedef T type;
};

And then:

int a = std::identity<unsigned char>::type('0');

std::identity<unsigned char>::type is a simple-type-specifier , and its type is simply the type of the template parameter.

Of course, you get a two-for-one with static_cast . This is the preferred casting method anyway.

在C ++中首选的方法是使用static_cast如下所示:

int a = static_cast<unsigned char>( '0' );

Try to add brackets int a = (unsigned char)('0');

or

typedef unsigned char uchar;

//inside main
int a = uchar('0');

No, it isn't - a function-style cast cannot have a space in its name.

A case for a C-style cast perhaps:

int main() {
    unsigned char c = (unsigned char) '0' ;
}

我很确定这是微软的扩展。

No, it isn't. But why the cast in the first place? This is perfectly valid,

int a = '0';

Why are you even trying to cast from char to unsigned char and assigning that to an int? You're putting an unsigned value into a signed int (which is legal, but uncool).

Writing '0' gives you a char with value 48. You can try

int i = (int) '0';

That way, you take the char, cast it to an int, and use it. You could even say

int i = '0';

And that would do the same thing. What exactly are you trying to do?

Are you trying to get the integer 0 or the character '0' into it? The character '0' on most implementations namely is just the integer 48 but put into 8 bits.

The only difference between a char and an int is that char must be smaller or equal to short int. and int must be larger or equal than short int accordingly, this usually makes char 8 bits, short in 16, and in 32 nowadays.

Stuf like 'a'+2 to get 'c' works namely. If you have an array that is long enough, you can also index it like array[' '] to get index 32.

If you're trying to cast it to the integer value 0, that would require an actual function that determines that.

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