Can't understand how the program is working

How does the Serial monitor display ‘12594’ when we write Serial.print(‘12’);?I have used single quotes intentionally.

void setup()
{
Serial.begin(9600);
Serial.print('12');
}

void loop()
{
}

I accidentally wrote “Serial.print(‘12’);” , but then I decided to compile it and upload it to see what it displays on Serial monitor.

Who knows and why should we care?

The output 12594 results from a programming error. Entering ‘12’ violates the rules for specification of a single 8 bit character and on my IDE, causes the compiler to emit a warning. It probably should be a fatal error rather than a warning.

We need to care to understand the basics…

This is not a fatal error.

When you output ‘12’ you are outputting 2 characters, a ‘1’ and then a ‘2’, this results in hex 31 or dec 49 being transmitted followed by a 32hex / 50dec, if you concatinate the two into a single integer then you get 12594, sending the 10 works out to be 12592, 11=12593

Binary of 49 = 00110001

Binary of 50 = 00110010

How these concatinate , depends on the compiler.

Here these concatinate as : 00110001 00110010

In some other compiler they may concatinate as :

00110010 00110001

The print statement is interpreting this as an integer (16bits) instead of two 8 bit characters because in C the character literal is defined as an int and your providing just the right number of 8 bit characters to make an int.

If you type = ‘312’ , then the compiler would consider last two characters only because the size of int is 2 bytes in Arduino IDE.

We need to care to understand the basics…

The behavior of any program resulting from a programming error is in general undefined, and is not included in anyone’s definition of “the basics”.

jremington:

We need to care to understand the basics…

The behavior of any program resulting from a programming error is in general undefined, and is not included in anyone’s definition of “the basics”.

Not to mention that this is more likely an issue with the Arduino library than the g++ compiler.

@OP: forget it. As jremington says, if you go outside the spec of the compiler, all bets are off. Just write correct code.