Is char signed or unsigned by default?

2018-12-31 02:44发布

In the book "Complete Reference of C" it is mentioned that char is by default unsigned.

But I am trying to verify this with GCC as well as Visual Studio. It is taking it as signed by default.

Which one is correct?

7条回答
美炸的是我
2楼-- · 2018-12-31 03:15

According to The C Programming Language book by Dennis Ritchie which is the de-facto standard book for ANSI C, plain chars either signed or unsigned are machine dependent, but printable characters are always positive.

查看更多
回忆,回不去的记忆
3楼-- · 2018-12-31 03:16

According to the C standard the signedness of plain char is "implementation defined".

In general implementors chose whichever was more efficient to implement on their architecture. On x86 systems char is generally signed. On arm systems it is generally unsigned (Apple iOS is an exception).

查看更多
梦该遗忘
4楼-- · 2018-12-31 03:23

C99 N1256 draft 6.2.5/15 "Types" has this to say about the signed-ness of type char:

The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char.

and in a footnote:

CHAR_MIN, defined in <limits.h>, will have one of the values 0 or SCHAR_MIN, and this can be used to distinguish the two options. Irrespective of the choice made, char is a separate type from the other two and is not compatible with either.

查看更多
大哥的爱人
5楼-- · 2018-12-31 03:31

As Alok points out, the standard leaves that up to the implementation.

For gcc, the default is signed, but you can modify that with -funsigned-char. note: for gcc in Android NDK, the default is unsigned. You can also explicitly ask for signed characters with -fsigned-char.

On MSVC, the default is signed but you can modify that with /J.

查看更多
与君花间醉酒
6楼-- · 2018-12-31 03:34

According to "The C++ Programming Language" by Bjarne Stroustrup, char is "implementation defined". It can be signed char or unsigned char depending on implementation. You can check whether char is signed or not by using std::numeric_limits<char>::is_signed.

查看更多
余生无你
7楼-- · 2018-12-31 03:34

Now, we known the standard leaves that up to the implementation.

But how to check a type is signed or unsigned, such as char?

I wrote a macro to do this:

#define IS_UNSIGNED(t) ((t)~1 > 0)

and test it with gcc, clang, and cl. But I do not sure it's always safe for other cases.

查看更多
登录 后发表回答