-1

I am learning C and I was messing around with deferent datatypes. I noticed something strange that the value of a char variable become zero every time I call scanf(*)

int main(){
    char mychar;
    char mychar2;
    char mychar3;

    scanf(" %d",&mychar);
    printf("char1 is :%d \n",mychar);

    scanf(" %d",&mychar2);
    printf("char1 is :%d\n",mychar);
    printf("char2 is :%d\n",mychar2);

    scanf(" %d",&mychar3);
    printf("char1 is :%d\n",mychar);
    printf("char2 is :%d\n",mychar2);
    printf("char3 is :%d",mychar3);


    return 0;
}

output

15
char1 is :15 
24
char1 is :0
char2 is :24
40
char1 is :0
char2 is :0
char3 is :40

since I am a total beginner In c programming, I just want to understand the reason of that behavior

  • 2
    If your compiler isn't telling you about the problem, turn up the warning options (`-Wall -Wextra` is a good start for gcc and clang) – Shawn Mar 20 '23 at 04:52
  • The `%d` format makes `scanf` expect an `int` but you provide a `char *`. As @Shawn says, you would be warned about this. – Amadan Mar 20 '23 at 04:56

2 Answers2

1

This behavior occurs because the type specifier and variable type of scanf function do not match. The variables mychar, mychar2, and mychar3 are char types, while using the %d format specifier for int type. This results in undefined behavior, which allows unexpected results to be observed.

To resolve this issue, you must use the %hhd format specifier used to read integer values from the character type

곽지훈
  • 56
  • 1
0

In your code, you are using the %d format specifier, which is used for reading integers, to read in a character. However, %d expects to read in an integer and store it in an int variable, which is why you are observing unexpected behavior when you try to read in a character.

To read in a character using scanf, you should use the %c format specifier instead. So, your scanf statements should look like this:

scanf(" %c",&mychar);

Sauron
  • 66
  • 1
  • 4
  • You can't read in a value like `15` , `24` or `40` using `%c` specifier. As the duplicate link suggests, `%hhd` (or `%hhu` for an `unsigned char`) should be used for the numeric format. – Amadan Mar 20 '23 at 04:57
  • Yes you are right I haven't paid attention to the output but if value inserted is to be of `int` type then the datatype of variables should be changed to `int` and `%d` specifier to be used. – Sauron Mar 20 '23 at 05:03