Home > Mobile >  Scanf affects another variable, a bug?
Scanf affects another variable, a bug?

Time:11-24

Here is a simple C code:

#include <stdio.h>

int main()
{
    char choice;
    int condition = 0;

    while (condition < 3)
    {
        printf("Type in a number: ");
        scanf("%hhd", &choice);        
        condition  ;        
        printf("%d\n", condition);
    }
}

I expect this to increment my condition variable each time a type in a character. But all of a sudden the output looks like this:

Type in a number: 1
1
Type in a number: 2
1
Type in a number: 3
1
Type in a number: 4
1
Type in a number: 5
1
Type in a number: 6
1
Type in a number: 7
1
Type in a number:

The problem goes away if I comment out scanf("%hhd", &choice);. How can it be? A bug? I have gcc 8.1.0 by mingw-w64.

Everything works well with clang, I just wonder why it is this way with gcc.


I have placed void as a parameter of main and it has solved the problem. Why?

CodePudding user response:

It looks like your C library might not be implementing the %hhd specifier for scanf correctly.

I tried this test fragment on my machine:

char a[] = "abcdef";
scanf("%hhd", &a[3]);

I typed 88, and the string changed to abcXef, confirming that %hhd wrote to just one byte of memory, as expected.

I don't see anything overtly wrong with the code you posted. On my machine, it prompts for just three inputs, because the condition variable increments correctly.

CodePudding user response:

You can't use %hhd to get a char.

You should use int choice; or scanf("%c", &choice);

  • Related