Home > Net >  Multiple Inputs in one scanf showing a miscellanous behaviour
Multiple Inputs in one scanf showing a miscellanous behaviour

Time:01-10

I was trying a simple calculation using long data types. Addition of three numbers. But while I take inputs in one scanf function, it take takes intial two input as zero.

#include <stdio.h>

int main()
{
long x,y,z;
printf("Input x,y,x:\n");
scanf("%lld %lld %lld",&x,&y,&z);
printf("Result: %lld\n",x y z);
return 0;
}

The code works perfectly fine in online compiler but not in my vscode. I checked the version of C we are using the same. I changed the code a little, i.e.,

scanf("%lld %lld %lld",&z,&y,&x);

and now it works perfectly fine. Why? How can just the arrangement of variable solved the issue. I did the initial code in int data type with %d format specifier, it worked perfectly fine but not the same with long and %lld. Can anyone explain why this happened or what is the error. Why does it works on online compiler but not my vs code.

I was expecting the sum of three numbers.

CodePudding user response:

The %lld specifier expect the address of a long long. You instead passed in the address of a long. Using the wrong format specifier triggers undefined behavior.

What most likely happened, given that you're using VS Code and therefore most likely running on Windows, on that system a long is 4 bytes while a long long is 8 bytes. So when scanf attempts to read a value, it writes 8 bytes into the the pointer it's given instead of 4, writing past the end of a variable and most likely into another.

The online compiler you're using is probably using gcc which has an 8 byte long so it happens to work.

You should instead be using the %ld format specifier which expects the address of a long.

scanf("%ld %ld %ld",&x,&y,&z);

CodePudding user response:

It's happening because you have used the wrong format specifier of long. Either declare the variables as long and use the format specifier as %ld or declare the variables as long long and use the format specifier as %lld

  • Related