Is the NULL pointer implicitly converted to type (int*) when we use "if(ptr==NULL)" for an integer pointer ptr?

StackOverflow https://stackoverflow.com/questions/16563342

문제

I know that a NULL pointer is (void*)0.But what happens when we use statements like the following:

  if(ptr==NULL)

where ptr can be a char,float or int pointer?Is NULL guaranteed to be implicitly converted to the type on the left just as, for example, in C, the type returned by malloc() is void* but is implicitly converted to the type of the lvalue?

도움이 되었습니까?

해결책

Is NULL guaranteed to be implicitly converted to the type on the left? [...]

Yes.

According to section 6.3.2.3.4 of the ISO/IEC 9899:2011 C programming language standard:

Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

and to section 6.3.2.3.1

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

다른 팁

I know that a NULL pointer is (void*)0

Not necessarily. The macro NULL could be defined as 0, (void*)0 or something else. The only requirement is that it is compatible with a null pointer for the specific implementation. In theory, a compiler could define NULL as 1, but in practice nobody does that.

Is NULL guaranteed to be implicitly converted to the type on the left

Yes, any expression where a null pointer is used together with another kind of pointer yields a null pointer. This has nothing to do with some implementations defining NULL as (void*). The C standard simply guarantees null pointer conversions, no matter the NULL macro.

in C, the type returned by malloc() is void* but is implicitly converted to the type of the lvalue?

Yes, in C a void* will always be implicitly converted to/from a pointer of another type (in C++, you would however need an explicit cast).

The magic happens because of the (void*) part. A void pointer can point to anything. So comparing any pointer to NULL is quite okay.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top