-1

My question is based on a CodeChef problem called Lucky Four.

This is my code:

int count_four() {
  int count = 0;
  char c = getchar_unlocked();
  while (c < '0' || c > '9')
    c = getchar_unlocked();
  while (c >= '0' && c <= '9') {
    if (c == '4')
      ++count;
    c = getchar_unlocked();
  }
  return count;
}

int main() {
  int i, tc;
  scanf("%d", &tc);
  for (i = 0; i < tc; ++i) {
    printf("%d\n", count_four());
  }
  return 0;
}

Let's say I make a slight change to count_four():

int count_four() {
  int count = 0;
  char c = getchar_unlocked();
  while (c >= '0' && c <= '9') {
    if (c == '4')
      ++count;
    c = getchar_unlocked();
  }
  while (c < '0' || c > '9') // I moved this `while` loop
    c = getchar_unlocked();
  return count;
}

This is my output after moving the while loop below the other one:

0
3
0
1
0

instead of:

4
0
1
1
0

The input used to test the program:

5
447474
228
6664
40
81  

Why is this happening? How do getchar() and getchar_unlocked() work?

fenceop
  • 1,439
  • 3
  • 18
  • 29

1 Answers1

1

getchar_unlocked is just a lower level function to read a byte from the stream without locking it. In a single thread program, it behaves exactly like getchar().

Your change in the count_four function changes its behavior completely.

The original function reads the standard input. It skips non digits, causing an infinite loop at end of file. It then counts digits until it gets a '4'. The count is returned.

Your version reads the input, it skips digits, counting occurrences of '4', it then skips non digits, with the same bug on EOF, and finally returns the count.

chqrlie
  • 131,814
  • 10
  • 121
  • 189