Search code examples
carrayswindowsvisual-studiokbhit

Why do I get different outputs by using different loops?


I made a code that inputs four letters, and prints an '*' in place of each one, as in a password. The working code is this:

#include <stdio.h>
#include <conio.h>
int main()
{
    int c = 0;
    char d[4];
    printf("Enter a character:");
    while (1)
    {
        if (_kbhit())
        {
            d[c] = _getch();
            printf("*");
            c++;
        }
        if (c == 4)
            break;
    }
    system("cls");
    for (c = 0; c <= 3; c++)
        printf("%c", d[c]);
}

Now I have two questions: 1) Why do I get four ╠'s when I change the loop to:

for (c = 0; c <= 4;c++)
    {
        if (_kbhit())
        {
            d[c] = _getch();
            printf("*");
        }
    }

and 2) Why do I get an extra ╠ at the end when I change the second loop's upper limit to c<=4?

The second loop being this:

for (c = 0; c <= 3; c++)
        printf("%c", d[c]);

Solution

  • Cause the for loop iterates 4 times no matter if _kbhit() returns true or false. The while loops until _kbhit() returns true 4 times

    For the second question, d[4] is out of the bounds of the array, the same value is just coincidence