0

I have seen in my legacy embedded code that people are using signed char as return type. What's the need to put signed there? Isn't that implicit that char is nothing but signed char.

dexterous
  • 6,422
  • 12
  • 51
  • 99

3 Answers3

1

char, signed char, and unsigned char are all distinct types.

Your implementation can set char to be either signed or unsigned.

unsigned char has a distinct range set by the standard. The problem with using simply char is that your code can behave differently on different platforms. It could even be a 1's complement or signed magnitude type with a range -127 to +127.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Because no-one in the candidate duplicate answer cited the right paragraph from the spec:

6.2.5 [Types], paragraph 15

The three types char, signed char, and unsigned char are collectively called the character types. The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char

So char could be either. (FWIW, I believe I ran into char = unsigned char in JNI.)

Community
  • 1
  • 1
lockcmpxchg8b
  • 2,205
  • 10
  • 16
  • I picked a different duplicate for closing. If you like, you can copy/paste this answer and post it there instead. – Lundin Nov 24 '17 at 08:33
  • That dupe answers a slightly different question. It's close enough to answer this one, but doesn't really need any more contribution. – lockcmpxchg8b Nov 24 '17 at 08:34
  • You might find other ways to switch more common compilers (most of them) to `unsigned char`. – autistic Nov 24 '17 at 08:39
0

From CppReference:

Character types

  • signed char - type for signed character representation.
  • unsigned char - type for unsigned character representation. Also used to inspect object representations (raw memory).
  • char - type for character representation. Equivalent to either signed char or unsigned char (which one is implementation-defined and may be controlled by a compiler commandline switch), but char is a distinct type, different from both signed char and unsigned char.

So if you want to ensure that you're using either an unsigned char or a signed char, specify it explicitly. Otherwise there'd be no guarantee whether it'll be signed or not.

iBug
  • 35,554
  • 7
  • 89
  • 134