Miscellaneous functions undergo implicit conversions in C?

Viewed 49

Well, function prototype arguments do implicit conversions, I was wondering if in this example, there is also implicit conversion or not? And if there is no conversion why does it happen? Since what other function prototypes do this conversion?

#include <stdio.h>

int main(void)
{ 
    unsigned char a;
    scanf("%d", &a); // conversion implicit or not ?
    printf("a = %d\n", a); // conversion implicit or not ?
    return 0;
}
2 Answers
  1. The scanf will write outside the space occupied by the variable - UB. There is no conversion here.

  2. unsigned char value is being promoted to int and passed to the print. But it is not because of the format.

The variable arguments to scanf and printf will only undergo the default argument promotions. This means that arguments of type float are promoted to type double and integer types smaller than int will be promoted to int. Note that this does not apply to pointers.

In the case of scanf, the %d format specifier is expecting an int * but you're passing in an unsigned char *. These types are not compatible so you have undefined behavior.

In the case of printf, %d expects an int. The unsigned char you're passing in gets promoted to int so in this case it is valid.

Related