Is casting in this way going to cause issues?

snprintf(time_str2, sizeof time_str2, "%d:%02d",(int8_t)min_counter, (int8_t)sec_counter);

Should I be casting within that function? Should I do that elsewhere first? Is this going to cause unknown issues?
This is for a timer, and the variables min_counter and sec_counter of course are type Unsigned Long.

Why are minutes and seconds unsigned long?

What is the time string supposed to represent? If it is elapsed time, what is the maximum number of minutes? What happens if seconds > 59?

... and why "of course"?

If you cast them to a byte and their value exceeds 255, the converted value will overflow.

This program should answer your question about "issues":

void setup() {
  Serial.begin(115200);
  while (!Serial);
  for (unsigned long i = 1; i < 1000; i += 20) Serial.println((int8_t) i);
}
void loop() {}

Sorry, they weren't going to exceed that. I was looking over some old code and apparently I changed the variables to uint8_t long ago.. Probably should not have assumed, and I should probably update the snprintf


uint8_t  min_counter = 0;
uint8_t    sec_counter = 0;

/* other code */
void elapsedTimer() {

  elapsedTime = currentMillis - startTime;

  min_counter = elapsedTime / 60000;
  sec_counter = (elapsedTime % 60000) / 1000;
 
}
snprintf(time_str2, sizeof time_str2, "%d:%02d",(int8_t)min_counter, (int8_t)sec_counter);

Your snprintf format string indicates you are passing two int arguments, but the actual arguments are actually passed as int8_t. That is not going to print the correct values.

the variables should be defined as the appropriate size needed for the code. the format string can specify the size/type of variable: "%u", "%ld"

Should. Before being placed on the "stack" they should be converted to int. I believe the C standard doesn't allow anything smaller to be passed as an argument. This appears to confirm.

But, the value sizes really should match the formats.

Ok, I was passing int16_t variable values into a function that was taking const int16_t as arguments.. Not sure why that was really causing the very strange behavior, but when I changed the types from const, it fixed everything. Very elusive to figure out because that code portion was pretty old and worked in other code, but it also was being passed the information correctly in the other code!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.