msg_324.c revision 1.3 1 1.3 rillig /* $NetBSD: msg_324.c,v 1.3 2021/01/05 23:20:53 rillig Exp $ */
2 1.1 rillig # 3 "msg_324.c"
3 1.1 rillig
4 1.1 rillig // Test for message: suggest cast from '%s' to '%s' on op %s to avoid overflow [324]
5 1.1 rillig
6 1.2 rillig /*
7 1.2 rillig * This warning applies to binary operators if the result of the operator
8 1.2 rillig * is converted to a type that is bigger than the operands' result type
9 1.2 rillig * after the usual arithmetic promotions.
10 1.2 rillig *
11 1.2 rillig * In such a case, the operator's result would be truncated to the operator's
12 1.2 rillig * result type (invoking undefined behavior for signed integers), and that
13 1.2 rillig * truncated value would then be converted. At that point, a few bits may
14 1.2 rillig * have been lost.
15 1.2 rillig */
16 1.2 rillig
17 1.2 rillig /* lint1-flags: -g -S -w -P */
18 1.2 rillig
19 1.2 rillig void
20 1.2 rillig example(char c, int i, unsigned u)
21 1.2 rillig {
22 1.2 rillig long l;
23 1.2 rillig unsigned long ul;
24 1.2 rillig
25 1.2 rillig l = c + i;
26 1.2 rillig l = i - c;
27 1.2 rillig ul = c * u;
28 1.2 rillig ul = u + c;
29 1.2 rillig ul = i - u;
30 1.2 rillig ul = u * i;
31 1.2 rillig l = i << c;
32 1.2 rillig
33 1.2 rillig /*
34 1.2 rillig * The operators SHR, DIV and MOD cannot produce an overflow,
35 1.2 rillig * therefore no warning is necessary for them.
36 1.2 rillig */
37 1.2 rillig l = i >> c;
38 1.2 rillig ul = u / c;
39 1.2 rillig ul = u % c;
40 1.3 rillig
41 1.3 rillig /*
42 1.3 rillig * Assigning the result of an increment or decrement operator to a
43 1.3 rillig * differently-sized type is no unusual that there is no need to warn
44 1.3 rillig * about it. It's also more unlikely that there is an actual loss
45 1.3 rillig * since this only happens for a single value of the old type, unlike
46 1.3 rillig * "ul = u * u", which has many more possibilities for overflowing.
47 1.3 rillig */
48 1.3 rillig ul = u++;
49 1.3 rillig ul = ++u;
50 1.3 rillig ul = u--;
51 1.3 rillig ul = --u;
52 1.2 rillig }
53