Chars not behaving as expected (unsigned?) in Particle Dev tool /cloud compiler

This might be programming 102 and I’m missing something obvious as it’s been a little while since i’ve done any serious programming.

I was whipping up a little proof of concept on my photon using the Particle Dev app. I borrowed an arduino sketch for the shield i’m using:
Which seemed to run, but get stuck in an infinite loop. I did a little digging and it would appear that the offending loop is:

char i;
for (i=31;i>=0;i–)

The Particle reference docs suggests that chars are signed and so I would assume that when i=0 i-- is going to give “-1”. But Serial.print((int)i); seems to suggest it goes to 255.(hence the infinite loop)

The fix is pretty simple - I defined ‘i’ instead as an int/int8_t and it works as designed, but I’d really like to know why it didn’t work the first time?

Have i missed something obvious/generic (although presumably that same code worked fine on the arduino they wrote it for) - or is this an anomaly with the particle dev tool / cloud compiler?

Hi @BlakeT

The type char is just badly defined for anything doing arithmetic, like your loop index. The C standard actually says char can be signed or unsigned, depending on the implementation. In the gcc compiler, there is a flag that tells the compiler how to treat it so you can have it either way. Just avoid char for anything arithmetic. Here’s a Stack Overflow article to read:

The types you do want to use are things like uint8_t and int32_t when you want to reliably be certain you are getting an unsigned 8-bit or signed 32-bit type.


Thanks, I wouldn’t have written it that way myself, so I’m happy with the solution.

But I’m guessing that GCC option hasn’t been configured in the cloud compiler in such a way that the results reflect the photon reference docs which are pretty clear about it being signed and ok for arithmetic.