xref: /netbsd-src/tests/usr.bin/xlint/lint1/d_alignof.c (revision 7d62b00eb9ad855ffcd7da46b41e23feb5476fac)
1 /*	$NetBSD: d_alignof.c,v 1.8 2022/06/22 19:23:18 rillig Exp $	*/
2 # 3 "d_alignof.c"
3 
4 /* https://gcc.gnu.org/onlinedocs/gcc/Alignment.html */
5 
6 unsigned long
7 leading_and_trailing_alignof_type(void)
8 {
9 	return __alignof__(short);
10 }
11 
12 unsigned long
13 leading_alignof_type(void)
14 {
15 	return __alignof(short);
16 }
17 
18 unsigned long
19 plain_alignof_type(void)
20 {
21 	/* The plain word 'alignof' is not recognized by GCC. */
22 	/* expect+2: error: function 'alignof' implicitly declared to return int [215] */
23 	/* expect+1: error: syntax error 'short' [249] */
24 	return alignof(short);
25 }
26 /* expect-1: warning: function 'plain_alignof_type' falls off bottom without returning value [217] */
27 
28 unsigned long
29 leading_and_trailing_alignof_expr(void)
30 {
31 	return __alignof__ 3;
32 }
33 
34 unsigned long
35 leading_alignof_expr(void)
36 {
37 	return __alignof 3;
38 }
39 
40 unsigned long
41 plain_alignof_expr(void)
42 {
43 	/* The plain word 'alignof' is not recognized by GCC. */
44 	/* expect+2: error: 'alignof' undefined [99] */
45 	/* expect+1: error: syntax error '3' [249] */
46 	return alignof 3;
47 }
48 /* expect-1: warning: function 'plain_alignof_expr' falls off bottom without returning value [217] */
49 
50 
51 /*
52  * As with 'sizeof', the keyword '__alignof__' doesn't require parentheses
53  * when followed by an expression.  This allows for the seemingly strange
54  * '->' after the parentheses, which in fact is perfectly fine.
55  *
56  * The NetBSD style guide says "We parenthesize sizeof expressions", even
57  * though it is misleading in edge cases like this.  The GCC manual says that
58  * '__alignof__' and 'sizeof' are syntactically the same, therefore the same
59  * reasoning applies to '__alignof__'.
60  */
61 unsigned long
62 alignof_pointer_to_member(void)
63 {
64 	struct s {
65 		unsigned long member;
66 	} var = { 0 }, *ptr = &var;
67 
68 	return __alignof__(ptr)->member + ptr->member;
69 }
70