-
Notifications
You must be signed in to change notification settings - Fork 160
/
auto.cpp
75 lines (62 loc) · 1.51 KB
/
auto.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
# auto
C++11 keyword
Completelly differs in meaning with the useless C `auto` keyword.
Variable type is infered based on return value of initialization.
Reduces code duplication, since it allows us to not write explicitly types everywhere.
Major application: create an iterator without speficying container type.
*/
#include "common.hpp"
int main() {
#if __cplusplus >= 201103L
// Basic usage.
{
// The compiler infers the type of i from the initialization.
auto i = 1;
assert(typeid(i) == typeid(int));
}
// Two different types on a single declaration. Nope.
{
// ERROR: inconsistent types.
{
//auto
//i = 1,
//s = std::string("abc")
//;
}
// OK for single type.
{
auto
i = 1,
j = 2
;
assert(typeid(i) == typeid(int));
assert(typeid(j) == typeid(int));
}
}
// Reference.
{
int i = 1;
auto& ai = i;
ai = 2;
assert(i == 2);
}
// ERROR: must initialize immediately. How could the compiler deduce type otherwise?
{
//auto i;
//i = 1;
}
// If initialized from reference, discards the reference, while decltype keeps it.
{
int i = 0;
int& ir = i;
auto ir2 = ir;
ir2 = 1;
assert(i == 0);
}
// Array. Seems not.
{
//auto is[]{1, 0};
}
#endif
}