Does the compiler allow 'char * k = false'? What for?

I found the compiler behavior strange from my point of view, it allows you to assign the value Boolean * char .

 char * k= false; 

Why? But after assigning * char is still not initialized. Why compilers do not allow to assign value int ?

+4
source share
4 answers

It will implicitly convert the boolean false to an integer with a value of 0 and thus declare a NULL pointer. It is no different from

 char* k = 0; 

which is valid syntax

+5
source

C ++ 03 Standard, # 4.10:

The null pointer constant is the integral constant expression (5.19) of the rvalue of an integer type that is zero.

5.19

An integral constant expression can include only literals (2.13), counters, constant variables or static integral data elements or enumeration types initialized with constant expressions (8.5), asymmetric parameters of integral or enumerated types and sizeof expressions.

false is a boolean literal, so it falls into the category of constant expression, so it can qualify as a null pointer constant.

+2
source

false and true are shortcuts for 0 and 1 . For a pointer, you use NULL , which define NULL 0 . So this is the correct syntax.

0
source

The compiler allows this because in C ++, false matches 0 and NULL .

Personally, at least for assignments, it’s easier for me to understand and more correctly use NULL to indicate a null pointer.

Btw, before C ++, on some NULL systems was actually a macro defined as (void*)0xffff ; some information about this can be found in this answer .

0
source

Source: https://habr.com/ru/post/1441751/


All Articles