简体   繁体   English

编译器允许'char * k = false'?为什么?

[英]compiler allows 'char * k= false'? Why?

I found strange from my point of view compiler behavior, It allows assign Boolean value to * char . 我从我的角度看编译器行为发现很奇怪,它允许将布尔值赋给* char

char * k= false;

Why? 为什么? But after assignment * char is still not initialized. 但是在赋值后,char仍未初始化。 Why compilers doesn't allows assign int value? 为什么编译器不允许赋值int值?

It will be implicitly converting the boolean value false to an integer with value zero and as such declaring a NULL pointer. 它将隐式地将布尔值false转换为值为零的整数,并因此声明NULL指针。 It is effectively no different from 它实际上没有什么不同

char* k = 0;

which is valid syntax 这是有效的语法

C++03 Standard, #4.10: C ++ 03标准,#4.10:

A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero. 空指针常量是整数类型的整数常量表达式(5.19)rvalue,其值为零。

5.19: 5.19:

An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type tem- plate parameters of integral or enumeration types, and sizeof expressions. 一个整数常量表达式只能包含文字(2.13),枚举数,常量变量或用常量表达式(8.5)初始化的整数或枚举类型的静态数据成员,整数或枚举类型的非类型模板参数,以及sizeof表达式。

false is a boolean literal, therefore it falls into the category of a constant expression, so it can qualify as a null pointer constant. false是一个布尔文字,因此它属于常量表达式的类别,因此它可以限定为空指针常量。

false and true are shortcuts for 0 and 1 . falsetrue01快捷方式。 For pointer you use NULL which define NULL 0 . 对于指针,使用NULL define NULL 0 So it correct syntax. 所以它正确的语法。

The compiler allows it because in C++ false is the same as 0 and NULL . 编译器允许它,因为在C ++中false0NULL相同。

Personally, at least for assignments, I find it easier to understand and more correct to use NULL to indicate a null pointer. 就个人而言,至少对于作业,我发现使用NULL来表示空指针更容易理解和更正确。

Btw, before C++, on some systems NULL was actually a macro defined as (void*)0xffff ; 顺便说一句,在C ++之前,在某些系统上, NULL实际上是一个定义为(void*)0xffff的宏; some background on that can be found in this answer . 这个答案中可以找到一些背景知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM