What is the actual use of "signed" keyword?

C++

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

In the case of int, there's no difference. It only makes a difference with char, because

  1. it is not defined whether char is signed or unsigned, and
  2. char, signed char, and unsigned char are three distinct types anyway.

So you should use signed if you need a signed char (which is probably rarely). Other than that, I can't think of a reason.

Solution 3 - C++

signed is the default integer type. So no, there is no difference in the example you gave. There is a difference only in the case of char.

Source: C++ Reference

Solution 4 - C++

There is no difference between the two where int's are concerned. You might include the word signed for formatting if you are also declaring unsigned int's so that they are easier to line up and make readable, but for all intents and purposes you don't need to use the signed keyword.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErik WView Question on Stackoverflow
Solution 1 - C++CB BaileyView Answer on Stackoverflow
Solution 2 - C++WintermuteView Answer on Stackoverflow
Solution 3 - C++YellowsView Answer on Stackoverflow
Solution 4 - C++hvanbrugView Answer on Stackoverflow