Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

c++ - What is the actual use of "signed" keyword?

I know that unsigned integers are only positive numbers (and 0), and can have double the value compared to a normal int. Are there any difference between

int variable = 12;

And:

signed int variable = 12;

When and why should you use the signed keyword?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is only one instance where you might want to use the signed keyword. signed char is always a different type from "plain" char, which may be a signed or an unsigned type depending on the implementation.

C++14 3.9.1/1 says:

It is implementation-defined whether a char object can hold negative values. Characters can be explicitly declared unsigned or signed. Plain char, signed char, and unsigned char are three distinct types [...]

In other contexts signed is redundant.


Prior to C++14, (and in C), there was a second instance: bit-fields. It was implementation-defined whether, for example, int x:2; (in the declaration of a class) is the same as unsigned int x:2; or the same as signed int x:2.

C++11 9.6/3 said:

It is implementation-defined whether a plain (neither explicitly signed nor unsigned) char, short, int, long, or long long bit-field is signed or unsigned.

However, since C++14 this has been changed so that int x:2; always means signed int. Link to discussion


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...