The principle of accepting various operands for a ternary operator in C

There are many typescasting types to ensure that assignment operations such as implicit type conversion (forward) and explicit type conversion (truncation), but I'm not sure how this works for pointer type conversion for a ternary operator.

#include <stdlib.h>

int main (void)
{
    (void)((rand() ? (char*)NULL :        NULL) + 1);
    /*     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        -> expression A */

    /* GCC Warning: pointer of type โ€˜void *โ€™ used in arithmetic */
    (void)((rand() ? (char*)NULL : (void*)NULL) + 1);
    /*     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        -> expression B */

    return 0;
}

Apparently, the compiler treats the expression A as a type char*, and B as a type void*.

I have two questions:

  • I checked the pre-processed code, and NULLexactly grown up ((void*)0), so why ((void*)0)and (void*)((void*)0)different types?

  • According to expression B, why does the compiler apply a type char*to a type void*, but not vice versa?

+4
2

:

6.5.15

.
:

/-/

- .
- , - ;
- - void.

(char*)NULL, () , NULL, .

ยง6 :

, , - , - , - ,

: char*, - , char*.

void*. ( , ). ( ):

... , ; , void void, void.

, ?: void*. .


, ?: , " C" .

NULL, , 0, (void*). .

, , , , 0 (void*)0.

6.3.2.2 :

0 cast to type void *, . , , , .

So (void*)NULL - , . .

: , .

+1

:

0 (void*)0 - , :

, ; (6.5.15)

(void*)((void *)0) - , (NULL):

0 cast to type void *, . , , , . (6.3.2.3 3)

, :

void void, void. (6.5.15)

+1

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


All Articles