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