This is where limits.h is useful. It may seem like a pain but to be safe you have to check the limits. In your first example, do this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define UB(...) do { printf("%s:%d: Undefined behaviour detected\n", __FILE__, __LINE__); exit(-1); } while(0)
int main(void) {
char c = 125;
if (c > CHAR_MAX - 10)
UB();
c += 10;
printf("%d\n",c);
return 0;
}
If you do lots of operations and want to guarantee that they are safe, then you could define some convenience macros
Code:
#define SAFE_ADD(VAR, AMOUNT) do { \
if (VAR > CHAR_MAX - (AMOUNT)) \
UB(); \
VAR += (AMOUNT); \
} while(0)
Looks a bit ugly but then you can do something like this instead of the above check each time you operate on c
Code:
int amt;
scanf("%d", &amt);
char c = 125;
SAFE_ADD(c, amt);
printf("%d\n",c);