Confusion in ternary operator and typecasting

后端 未结 2 1059
半阙折子戏
半阙折子戏 2021-01-05 08:42

I gone through this question -

why the result of : 1 ? (int *)0 : (void *)0
differs to the result of : 1 ? (int *)0 : (void *)1

2条回答
  •  心在旅途
    2021-01-05 08:56

    So effeffe already answered on why the two expressions differ:

    1 ? (int *) 0 : (void *) 0  // yield (int *) 0
    1 ? (int *) 0 : (void *) 1  // yield (void *) 0
    

    To answer this question now:

    How to check the result ?

    With gcc you can use typeof extension and __builtin_types_compatible_p builtin function:

    // The two expressions differ
    printf("%d\n", __builtin_types_compatible_p(typeof(1 ? (int *) 0 : (void *) 0), typeof(1 ? (int *) 0 : (void *) 1)));
    
    // First expression yield (int *) 0
    printf("%d\n", __builtin_types_compatible_p(typeof((int *) 0), typeof( 0 ? (int *)0 : (void *)0  )));
    
    // Second expression yield (void *) 0
    printf("%d\n", __builtin_types_compatible_p(typeof((void *) 0), typeof( 1 ? (int *)0 : (void *)1  )));
    

提交回复
热议问题