-
Notifications
You must be signed in to change notification settings - Fork 33
/
2.32.txt
37 lines (25 loc) · 1.3 KB
/
2.32.txt
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
Exercise 2.32: Is the following code legal or not? If not, how might you make
it legal?
int null = 0, *p = null;
By Faisal Saadatmand
Illegal: though initialized from a literal, i.e. a constant, null is a plain
int object with a memory address, and thus, it is not a constant expression. As
such, it cannot be used to initialize p, which is a pointer to an int.
Assuming that the intention of the code were simply to define p as a null
pointer, the best way to do so is to use the standard library defined literal
type nullptr:
int *p = nullptr; // C++ style; preferred
Alternatively, we could use the C-style NULL or 0 (NULL may require cstdlib or
a macro definition):
int *p = NULL; // C-style
int *p = 0;
Finally, we can make the above code legal by defining null as constexpr const
pointer to an int (low-level const is implied).
constexpr int *const null = 0; // evaluated at compile time
int *p = null; // OK: assign 0 to p
This approach, however, has one major drawback. It is not generic, and thus,
works only with pointers to int. For example we would be able to assign null to
a pointer to a double:
constexpr int *const null = 0; // null is a const pointer to a const int
double *p = null; // error: p is a pointer to a double
Note: with the class temples (chapter 16) this drawback can be overcome.