Does this invoke undefined behaviour?

后端 未结 3 1509
梦毁少年i
梦毁少年i 2020-12-06 14:27

Consider the following C program:

#include 

int main(){
    int a =-1;
    unsigned b=-1;
    if(a==b)
        printf(\"%d %d\",a,b);
    els         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-06 14:56

    The standard isn't 100% clear on this point. On one hand, you get the specification for va_arg, which says (§7.15.1.1/2):

    If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases:

    • one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types;
    • one type is pointer to void and the other is a pointer to a character type.

    On the other hand, you get the specification of printf (§7.19.6.1/9):

    If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."

    Given that it's pretty much a given that printf will retrieve arguments with va_arg, I'd say you're pretty safe with values that can be represented in the target type, but not otherwise. Since you've converted -1 to an unsigned before you pass it, the value will be out of the range that can be represented in a signed int, so the behavior will be undefined.

提交回复
热议问题