Is there any special function built into the c++ library that accomplishes this?
Is there any special function built into the c++ library that accomplishes this?
Is there perhaps another way? I just recently started learning about c++, though I do have a background in java.
First and foremost, what are you trying to solve? Also, keep in mind, C++ has a char and an unsigned char. So unless you have a wonky implementation, you can assume that char is signed.
I got help from someone. So we are basically setting char variable x with 255. Then if x is less than 0 then char is unsigned, signed otherwise. Can you explain what is happening when char x = 255? Or is it as simple as storing 255 inside x?
Code:char x = 0xFF; if (x < 0) { printf("char is unsigned\n"); } else if (x >= 0){ printf("char is signed\n"); }
Last edited by asilvester635; 01-27-2017 at 06:09 PM.
Sorry, there was a mistake in my code. Her is the correct (I think) code.
Code:char x = 0xFF; if (x < 0) { printf("char is signed\n"); } else if (x >= 0){ printf("char is unsigned\n"); }
> char x = 0xFF;
This presumes that chars are 8-bit numbers, which isn't universally true.
The GCC compiler allows you to choose whether the basic 'char' type is signed or unsigned.
-funsigned-char
-fsigned-char
is_signed (see post #2) seems the best idea. Anything else is looking hacky if it's going to be anywhere near portable.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Salem is correct. A char is a byte but a byte isn't guaranteed to be 8 bits.
is_signed is the best approach. It requires more advanced C++ but it's the only true solution. Keep in mind, signed types are also not universally represented. There are myriad ways of laying out the representation of a signed integral type. Crude assignment like that will be unreliable and error prone.
Use is_signed.
Code:static_assert(std::is_signed<char>::value);
However, for the signed integer representation the standard only permits sign and magnitude, one's complement, and two's complement representations.Originally Posted by MutantJohn
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)