1 // RUN: %check_clang_tidy %s bugprone-dynamic-static-initializers %t -- -- -fno-threadsafe-statics
2
fact(int n)3 int fact(int n) {
4 return (n == 0) ? 1 : n * fact(n - 1);
5 }
6
7 int static_thing = fact(5);
8 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: static variable 'static_thing' may be dynamically initialized in this header file [bugprone-dynamic-static-initializers]
9
sample()10 int sample() {
11 int x;
12 return x;
13 }
14
15 int dynamic_thing = sample();
16 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: static variable 'dynamic_thing' may be dynamically initialized in this header file [bugprone-dynamic-static-initializers]
17
18 int not_so_bad = 12 + 4942; // no warning
19
20 extern int bar();
21
foo()22 int foo() {
23 static int k = bar();
24 // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: static variable 'k' may be dynamically initialized in this header file [bugprone-dynamic-static-initializers]
25 return k;
26 }
27
bar2()28 int bar2() {
29 return 7;
30 }
31
foo2()32 int foo2() {
33 // This may work fine when optimization is enabled because bar() can
34 // be turned into a constant 7. But without optimization, it can
35 // cause problems. Therefore, we must err on the side of conservatism.
36 static int x = bar2();
37 // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: static variable 'x' may be dynamically initialized in this header file [bugprone-dynamic-static-initializers]
38 return x;
39 }
40
foo3()41 int foo3() {
42 static int p = 7 + 83; // no warning
43 return p;
44 }
45