The triple (conditional) expression is of the wrong type

I found that these two implementations are NOT equal:

1.num = sign ? (int)va_arg(args, int) : (unsigned int)va_arg(args, unsigned int);

2.if (sign)
    num = (int)va_arg(args, int);
else    
    num = (unsigned int)va_arg(args, unsigned int);

first implementation, it always selects a false branch, no matter what the sign matters.

the second works as expected.

What's going on here? I am using GCC / ARM GCC 64bit

+4
source share
1 answer

I would suggest that the problem you are facing is the subtle, implicit progress that occurs in the statement ?:. The second and third operands are balanced with each other using ordinary arithmetic transformations. This is provided by C11 6.5.15:

, , , , , .

, , - , unsigned. , 2- 3- .

, :

#include <stdio.h>

int main (void)
{
  int x;
  if( (-1 ? (printf("Expression evaluates to -1\n"),-1) : 0xFFFFFFFF) < 0)
  {
    printf("-1 is < 0");
  }
  else
  {
    printf("-1 is >= 0");
  }
}

:

Expression evaluates to -1
-1 is >= 0

if/else ?:.

+4

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


All Articles