[SystemSafety] Correcting the screw-up (grovelling apologies)

Olwen Morgan olwen at phaedsys.com
Tue Jul 14 13:19:35 CEST 2020


Below is a (hopefully now correct) program to test the signedness of 
plain char:


#include <stdio.h>


/* program to test for signedness of plain char in C                   */

/* assumes that all integral types have an even number of bits */


static const char diag[2][9] = { "UNSIGNED", "SIGNED" };

int main (void)
{
     int ch1 = (char)2;
     int ch2 = (char)((ch1 << 2) + 2);

     printf("\nPlain char signedness test: ");

     while (ch2 != ch1)
     {
         ch1 = (char)ch2;
         ch2 = (char)((ch1 << 2) + 2);
     }

     printf ("ch1 = %i, plain char is %s\n", ch1, diag[ (ch1 < 0) ]);

     return 0;
}

Note the "anally obsessive" coding style: initialisation at declaration 
of all variables, none of the non-const variables is assigned to in more 
than one place in its scope (meaning that the local loop invariant can 
here be read directly from the code), and indexing into an array of 
strings to avoid branching and ensure that there are *exactly two* 
simple paths through the program.

Olwen




More information about the systemsafety mailing list