0

I have a problem with scanf() and printf() function in a snippet of code like this:

#include <stdio.h>

int main() {
    int a;
    int b;
    int c;
    scanf("%d %d", &a, &b);
    while (c >= 2) {
        c = a % b;
        a = b;
        b = c;
        printf ("%d\n", c);
    }
    return 0;
}

What I expect to happen, and happens in my brother's Code::Block, is for the program to wait for input from stdin and then print to stdout the results, one per line, until it reaches the highest common divisor.

However, when I type it in vi and then compile it with gcc and run the program from my terminal, the program correctly takes the input but exit without returning anything to stdout.

If I comment out the scanf() line and hardcode any number to a and b variables, everything works as expected.

I'm trying to learn C and I've read basic documentation on the functions, but I can't help to understand this kind of behaviour. I've tried to put a setbuf(stdout, NULL) before declaring variables but nothing changed.

Can somebody give me a clue?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
jxx
  • 9
  • 1
  • 5
    `c` is unitialized – Eraklon Mar 28 '20 at 22:40
  • 3
    The compiler or the OS is effectively making `c` to be zero. If it isn't, then every so often when you execute it, it might print something on stdout. It's undefined behavior, essentially. – Jeff Holt Mar 28 '20 at 22:42

1 Answers1

1

There's nothing wrong with your scanf and printf calls but, as others have mentioned, one obvious problem is that you are testing the value of an uninitialised variable (c).

Maybe, what you want is a do { ... } while (...); loop, rather than a simple while loop.

The following code will guarantee to execute the loop at least once and then, at the end of each loop, check whether or not to repeat it:

#include <stdio.h>
int main() {
    int a;
    int b;
    int c;
    scanf ("%d %d", &a, &b);
    do {
        c = a % b;
        a = b;
        b = c;
        printf ("%d\n", c);
    } while (c >= 2);
    return 0;
}

(Alternatively, initialise c with a value that is >= 2, i.e. use the declaration: int c = 3;.)

For further discussion of the do .. while loop, see here: 'do...while' vs. 'while'

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 1
    There is something wrong with the `scanf()`, although not the cause of the problem. The OP should check the return value to detect invalid input and avoid proceeding if `a` or `b` were not read properly. – chqrlie Mar 29 '20 at 13:34
  • @chqrlieforyellowblockquotes I can't/won't argue with that! :) – Adrian Mole Mar 29 '20 at 15:02