TransWikia.com

Anomalous scanf behaviour in C

Stack Overflow Asked by Parth Sarthi Sharma on November 17, 2021

I am trying to run the following code in C:

#include <stdio.h>
#include <stdint.h>

void main(){
    int firstNum = 5;
    int16_t secondNum;
    
    printf("Please enter the first number: ");
    scanf("%d", &firstNum);
    printf("Please enter the second number: ");
    scanf("%d", &secondNum);
    
    printf("%d %dn", firstNum, secondNum);
}

And the output I am getting is as follows:

Please enter the first number: 13
Please enter the second number: 4
0 4

--------------------------------
Process exited after 1.877 seconds with return value 4
Press any key to continue . . .

Why is that so?

My IDE is Dev-C++. Compiler is TDM-GCC 4.9.2 64-bit Release. Program name is TestBit.c (if that is relevant?).

Note: When I change the line int16_t secondNum; to int secondNum;, the program works as intended.

3 Answers

The proper specifier for int16_t secondNum is from <inttypes.h>

// scanf("%d", &secondNum);
scanf("%" SCNd16, &secondNum);

Better code would check the return value.

if (scanf("%" SCNd16, &secondNum) == 1) {
  Success();
}

Answered by chux - Reinstate Monica on November 17, 2021

Try changing to: scanf("%hd", &secondNum);

%d is a 4-byte data specifier, int16_t is actually only 2 bytes.

More references: https://docs.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=vs-2019

Answered by Sprite on November 17, 2021

An int16_t is not the same thing as an int; so passing a pointer to one via scanf and pretending it is an int pointer can yield unexpected behaviour; thus your question.

Replace int16_t with int and your program works. For followup read the C Programming Language specification of types and what they mean.

Answered by mevets on November 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP