2

No matter what value I enter for x, the output for the value of y is always 1. Any ideas why?

#include <stdio.h>    
int main() {
    int x, y;
    y = scanf("%d", &x);
    printf("y = %d\n", y);
    return 0;
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
D. D.
  • 97
  • 1
  • 2
  • 10
  • 2
    A [good `scanf` (and family) reference](http://en.cppreference.com/w/c/io/fscanf) might be helpful. Especially read about what it returns. Oh and *think* a little, if you had a format string with multiple conversions (like e.g. `"%d %d"`), how would `scanf` be able to return all the values then? Reading [a good beginners book or two](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) should also be very good. – Some programmer dude Oct 22 '17 at 14:09
  • 2
    Read the manpage for scanf. You read one value. Of course y = 1/ – David Hoelzer Oct 22 '17 at 14:16
  • @xing entering `abc` with this code is UB – CIsForCookies Oct 22 '17 at 14:19
  • You are right by saying that printing 'y' wouldn't be ub but reading string with the %d format is ub by itself. Before invoking the printf – CIsForCookies Oct 22 '17 at 20:25
  • 3
    @CIsForCookies: Whoa, hold up - entering `"abc"` for *this code* would not be undefined behavior - it would be a *matching failure*, and `scanf` would return 0, leaving `"abc"` in the input stream. That's well-defined. What's UB is using an argument type other than `int *` for the `%d` conversion specifier. – John Bode Oct 22 '17 at 23:20
  • @JohnBode Thanks for that, I thought `scanf` had no check for these kind of bad iputs – CIsForCookies Oct 23 '17 at 10:40
  • 1
    @CIsForCookies: It’s not perfect - if you enter `”1bc”`, the `%d` specifier will convert and assign the `1`, leaving `”bc”` in the input stream. – John Bode Oct 23 '17 at 11:06

1 Answers1

3

From scanf(3) - Linux man page:

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

Since scanf return value is the number of items written (in your case, 1, since only 1 int was scanned), not the integer value of the scanned character

int main() {
    int x, y, z, n;
    n = scanf("%d", &x);
    printf("n = %d\n", n);                 // prints 1
    n = scanf("%d%d", &x, &y);
    printf("n = %d\n", n);                 // prints 2
    n = scanf("%d%d%d", &x, &y,&z);
    printf("n = %d\n", n);                 // prints 3
    return 0;
}
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124