Does compiler, Serial.print() treat char and int8_t types differently?

Hi,

apologies for not finding a rationale for the following behaviour so feel free to direct me with an appropriate link.

Although char and int8_t, as far as I have read, should be interchangeable (Arduino: Difference in "Byte" VS "uint8_t" VS "unsigned char" - Oscar Liang etc) they behave differently when Serial.print is called.

I presume this is by design but I would appreciate any guidance as to it rationale, where this is documented and whether I should, in general, be using "char" or more specific and portable "int8_t" terminology.

void setup() {
  Serial.begin(9600);
  int8_t varInt8 = 0x5a; // "Z"
  char varChr = 0x5a;
  Serial.println(varChr); //prints "Z" as expected
  Serial.println(varInt8); //prints 90 = (decimal) 0x5a
  Serial.println((char) varInt8); //prints "Z"
}

void loop() {
 }

best wishes,
Jason

char is printed as is. a byte is printed as text representation of the number

Thanks,

I have gathered that is happening: it was demonstrated in the code snippet. My confusion arises from my (perhaps limited) understanding that char and uint8_t were interchangeable and I would like to know where this is documented and if it applies more generally outside the Arduino IDE.

best wishes

jjkernelkrash:
Thanks,

I have gathered that is happening: it was demonstrated in the code snippet. My confusion arises from my (perhaps limited) understanding that char and uint8_t were interchangeable and I would like to know where this is documented and if it applies more generally outside the Arduino IDE.

best wishes

it is about different print fuctions, not about data types
there is a write() function which takes a byte and sends a byte

Arduino's Print class uses function overloading to allow any standard type to be printed. Some types are handled differently from others. Here is a simple sketch that demonstrates how a different overload of the function is called depending on the type of the argument:

void setup() {
  Serial.begin(9600);
  while (!Serial) {}
  Serial.println("hello");
  char foo = 'a';
  test(foo);
  int8_t bar = 'b';
  test(bar);
}

void loop() {}

void test(char x) {
  Serial.println("char overload");
}

void test(int8_t x) {
  Serial.println("int8_t overload");
}

Thanks,

that's interesting. I have found the relevant part of Print.h which shows the different overload behaviours and it is helpful in clarifying some of my confusion.

You point out that char and int8_t are not interchangeable (and it also seems that "signed char" and char are not interchangeable which is really making my head hurt). Getting back to the second part of my original question: is there any good advice/reference about data types with respect to both Arduino IDE behavior and how they relate to C++ programming more generally?

best wishes