这纯粹是一个哲学问题。我假设没有合理的上下文证明结果有用(给定nullptr
)。
据此-https://en.cppreference.com/w/cpp/language/integer_literal,整数文字的类型为int
,long int
,long long int
,unsigned int
,unsigned long int
或unsigned long long int
,如果该值可能是实现特定的例外的字面值不符合以上任何条件。这些类型都不能转换为void *
,除非文字的值是0。
不同的编译器对此处理方式不同。例如,考虑以下转换:
void g(void * p){}
void f(){
int i = 0;
void * p;
// p = i; // Fails. Also for other integral types.
p = 0; // Works. Also for 00, 0x0 and 0b0. Also when adding `u` and `l` suffixes.
g(0); // Also works.
// g(1); // Fails.
// Amazingly, even this seems to work with gcc, icc and msvc, but not with clang:
void * x = static_cast<int>(0);
// These works for icc and msvc, but fails with gcc and clang
p = static_cast<int>(0);
g(static_cast<int>(0));
}
使引擎编译器执行这些int
-> void *
转换的“幕后”会发生什么?
将使编译器执行这些int-> void *转换的“幕后操作”会发生什么?
编译器解析源。语法说0是文字。编译器将其视为文字0,因此可以将其转换为根据标准的任何指针类型。