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

The following compilations are in Visual Studio, but not compiled under g ++.

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

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

+7
c ++
source share
8 answers

No, this is not legal.

Converting an explicit type to a function style requires a simple type specifier, followed by a parenthesized list of expressions. (ยง5.2.3) unsigned char not a type specifier; this is due to a question raised by James .

Obviously, if unsigned char was a simple type specifier, that would be legal. A workaround should be 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 specifier of a simple type, and its type is just the type of the template parameter.

Of course, you get two-for-one with static_cast . In any case, this is the preferred casting method.

+11
source share

The preferred casting method in C ++ is to use static_cast as follows:

 int a = static_cast<unsigned char>( '0' ); 
+5
source share

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

or

 typedef unsigned char uchar; //inside main int a = uchar('0'); 
+3
source share

No, this is not so: when creating a function, there can be no space in the name.

Case for C-style custom, perhaps:

 int main() { unsigned char c = (unsigned char) '0' ; } 
+2
source share

I am sure this is a Microsoft extension.

+1
source share

No, it is not. But why are the actors in the first place? This is absolutely true

 int a = '0'; 
0
source share

Why are you even trying to make char into an unsigned char and assign it an int? You put an unsigned value in a signed int (which is legal, but uncool).

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

 int i = (int) '0'; 

So you take a char, throw it into an int and use it. You can even say

 int i = '0'; 

And it will do the same. What exactly are you trying to do?

0
source share

Are you trying to get the integer 0 or the character '0' in it? The "0" character for most implementations is just an integer 48, but placed in 8 bits.

The only difference between char and int is that char must be less than or equal to a short int. and int should be greater than or equal to the short int, respectively, this usually makes char 8 bits short at 16 and 32 for now.

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

If you are trying to apply it to an integer value of 0, this will require an actual function that defines this.

0
source share

All Articles