By default compiler is assuming char declaration as unsigned char instead of signed char (Compiler Version : gcc-arm-none-eabi-4_8-2014q3)

Asked by palachandra

/* C code to illustrate compiler consideration for char data type*/
/* By default compiler is assuming char declaration as unsigned char instead of signed char */
/* The below code snippet illustrate the same */

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char nValue1 = -1;
  signed char nValue2 = -1;

  printf("Testing : (char nValue1)\n");
  if(nValue1 > 0)
  {
      printf("\tError:\n");
      printf("\tTest Failed for nValue1\n");
      printf("\tCompiler considering char as unsigned char\n");
      printf("\tIn comparison check -1 nValue is assumed to be 0xff (255) instead of (-1)\n");
  }
  else
  {
   printf("\tSuccess:\n");
   printf("\tTest Passed for nValue1\n");
  }

  printf("\nTesting : (signed char nValue2)\n");
  if(nValue2 > 0)
  {
   printf("\tError:\n");
   printf("\tTest Failed for nValue2\n");
  }
  else
  {
   printf("\tSuccess:\n");
   printf("\tTest Passed for nValue2\n");
  }
  return (0);
}

/* Output of above Code */
Testing : (char nValue1)
 Error:
 Test Failed for nValue1
 Compiler considering char as unsigned char
 In comparison check -1 nValue is assumed to be 0xff (255) instead of (-1)

Testing : (signed char nValue2)
 Success:
 Test Passed for nValue2

Observation :
Ideally compiler should have considered as char as signed char instead of unsigned char.
Can you please comment on my observation.

Thanks and Regards,
Palachandra M V

Question information

Language:
English Edit question
Status:
Solved
For:
GNU Arm Embedded Toolchain Edit question
Assignee:
No assignee Edit question
Solved by:
palachandra
Solved:
Last query:
Last reply:
Revision history for this message
Freddie Chopin (freddie-chopin) said :
#1

There is no standard requirement for "char" to be explicitly "signed" or "unsigned" - it can be anyway the compiler would like it to be.

http://en.cppreference.com/w/c/language/arithmetic_types
"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 both unsigned char"

And in fact there are "-fsigned-char" and "-funsigned-char" switches for GCC.

Revision history for this message
palachandra (mvp-bhat) said :
#2

Hi Freddie,

Thank you for your reply.