简体   繁体   中英

the code doesn't work properly at output C

I tried to read 2 variables from the keyboard and to write them on the screen and I have a problem, the program display me only one..

#include <stdio.h>
#include <stdlib.h>

int main()
{
    short int n,x;
    scanf("%d",&n);
    scanf("%d",&x);
    printf("%d %d",n,x);
    return 0;
}

I introduced 14 and 15 and the program return me 0 and 15 can somebody tell me why?

Use %hd format specifier for short int Use %hu format specifier for unsigned int Use %d format specifier for int Use %ld format specifier for long int

#include <stdio.h>
#include <stdlib.h>

int main() {
  short int n, x;
  scanf("%hd", &n); // Notice %hd instead of %d for short int
  scanf("%hd", &x); // Notice %hd instead of %d for short int
  printf("%hd%hd", n, x);// Notice %hd instead of %d for short int
  return 0;
}

The formatters in scanf() and printf() doesn't match the type of your variables n and x .

%d uses the variables as they were int while int has probably the double number of bytes as short int . ( Integer types )

Hence, with the wrong formatters, scanf() uses the provided addresses wrong. For printf() it's a bit more complicated: The short int s are converted to int internally. ( Default argument promotions ) Hence, printing short int with %d (as they were int ) doesn't fail.

So, it's the scanf() what must be fixed.

Either use correct formatters:

#include <stdio.h>

int main()
{
    short int n,x;
    scanf("%hd",&n);
    scanf("%hd",&x);
    printf("%d %d",n,x);
    return 0;
}

Live Demo on ideone

or use correct variable type for the formatters:

#include <stdio.h>

int main()
{
    int n,x;
    scanf("%d",&n);
    scanf("%d",&x);
    printf("%d %d",n,x);
    return 0;
}

Live Demo on ideone

The formatting of scanf() and printf() families are very powerful and flexible but unfortunately very error-prone as well. Using them wrong introduces Undefined Behavior . The compiler is (usually) unable to recognize errors as the evaluation of formatters happens at run-time and inside the scanf() / printf() functions. So, they have to be used caaarefully.

%d assumes the variable to be of data type int .

Use the data type int :

int main()
{
    int n,x;
    scanf("%d",&n);
    scanf("%d",&x);
    printf("%d %d",n,x);
    return 0;
}

or use %hd instead of %d

int main()
{
    short int n,x;
    scanf("%hd",&n);
    scanf("%hd",&x);
    printf("%hd %hd",n,x);
    return 0;
}

Note, scanf("%d",&x); read a value and stores it to the memory addressed by &x . Since &x is treated as a 4 byte memory, 4 bytes are written to the address specified by &x .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM