Skip to main content
2 of 3
snprintf note

As Ignacio says, if the compiled size is the same both ways, look for something else. (But note that having the constants in flash memory (program memory) may still use about the same amount of RAM, and typically will take more program space.)

When I compile the code you showed (together with minor additions like declaration of variables) I show the array method using 4 bytes less code and 5 bytes more RAM than the if method, so there are tradeoffs.

You can replace the clunky if statement and its two lcd.prints with the following:

      lcd.print(hour>12? "am" : "pm");

Note that that line retains the two bugs that your if statement has, but it produces them more compactly. :) Your if statement prints pm for hours 0 through 12 and am for hours 13 through 23. Properly, a program should instead print like 12:xx am during hour 0 of the day, and forms 12:xx pm, 1:xx pm, ... 11:xx p.m. forms during hours 12 through 23.

The following lines of C can replace much of the code you showed. However, the printf library uses about 1300 bytes of program space, so the following compact-source-code approach cannot be recommended unless you are already loading some printf functions. It replaces the lines from if (hour>12) { hr = hour - 12; } ... to the end with

enum { bufsize=8 };
char buf[bufsize];
snprintf (buf, bufsize, "%02:02%s", hour%12, minute, hour>12? "pm" : "am");
lcd.print(buf);