Namespaces
Variants
Actions

Talk:c/language/operator other

From cppreference.com

[edit] Ternary operator code snippet

In the ternary operator section:


4) if one is a pointer and the other is a null pointer constant, the type is the type of that pointer

...

#define ICE(x) (sizeof(*(1 ? ((void*)((x) * 0l)) : (int*)1)))
 
// if x is an Integer Constant Expression then macro expands to
 
 sizeof( 1 ? NULL : (int *) 1)  // (void *)((x)*0l)) -> NULL
 
// according to point (4) this further converts into
 
 sizeof(int)


I believe there is a * missing in the code snippet, the macro should expand to sizeof(*(1 ? NULL : (int *)1)). The way it's currently written, it eventually expands to sizeof(int*), not sizeof(int).


Babbage (talk) 14:50, 15 July 2022 (PDT)

Good catch! On 64-bit platforms like LP64 we can even check it:
#include <assert.h>
#include <stddef.h>
 
int main(void)
{
    assert( sizeof(int*) == sizeof(   1 ? NULL : (int *) 1)  );
    assert( sizeof(int ) == sizeof( *(1 ? NULL : (int *) 1)) );
    /*                            --^-- missed dereference   */
    assert( 8 == sizeof( int* ) );
    assert( 4 == sizeof( int ) );
}

 It's fixed. --Space Mission (talk) 06:16, 16 July 2022 (PDT)