3

Consider following program:

#include <stdio.h>
int main()
{
    short a=9;
    //printf("%hi\n",a);
    printf("%d",a);  // LINE 6
}

According to this the format specifier for short type (signed) is %hi Is the short type variable always gets promoted automatically to int before performing any operation on it? Is it undefined behavior , If I use %d format specifier to print the value of variable in this program? I compiled it using gcc -Wall -Wextra -WFormat options but still compiler isn't showing any single warning. Why?

1 Answer 1

3
printf("%hi\n", a);

a is promoted to int as per the rules of default argument promotion of variadic functions.

Anyway as you use h specifier the implementation is allowed to expect the int value is within SHRT_MIN or SHRT_MAX limits. Passing a value outside the bounds is undefined behavior.

Of course printf("%i\n", a); is also valid because of the int promotion of a so using %hi conversion specification is not very usual.

7
  • where can I find the rules of default argument promotion of variadic functions. ?
    – Destructor
    Sep 11, 2015 at 17:06
  • 1
    @PravasiMeet see C Standard, in C99 see 6.5.2.2p7 for rules of promotion with variadic functions and 6.5.2.2p6 for what is the default argument promotions.
    – ouah
    Sep 11, 2015 at 17:08
  • 1
    False! The C standard only says (ISO 9899:2011§7.21.6.1¶7#h) “the argument will have been promoted according to the integer promotions, but its value shall be converted to short int or unsigned short int before printing” For me this does explicitly specify defined behaviour for int values outside the range from SHORT_MIN to SHORT_MAX, where the behaviour is as if the parameter was converted by printf to signed short/ unsigned short before printing.
    – fuz
    Sep 11, 2015 at 17:13
  • 1
    @ouah Hm... The wording is definitely unclear. Let me ask a question about this.
    – fuz
    Sep 11, 2015 at 17:23
  • 2
    @ouah Let's see what comes out of this.
    – fuz
    Sep 11, 2015 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.