简体   繁体   中英

Why can't I assign a scanf statement directly to a variable in C?

How is int a = scanf("%d", &a); different from int a; scanf("%d", &a); int a; scanf("%d", &a); ?

I need some help trying to understand how these two things work behind the scenes as they clearly output different results.

scanf is a standard input function in C.

The first thing you should learn about scanf is the 'return value'. Refer to the manual page for scanf by accessing man scanf if you're on Linux.

scanf returns the number of values read in from standard input. ie your scanf would return 1, as only one value has been read in, in this case.

So if you run

int a = scanf("%d", &a);

first the expression int a would create a new int variable of size int (4 bytes). Then scanf("%d", &a) would input a value of size int from your standard input. Say you enter 5.

But then as you are setting a to whatever scanf is returning, ie the number of values read from the standard input which is 1. so a would always be 1 no matter what value you enter into input.

Now, as for

int a; 
scanf("%d", &a); 

What you are doing is, first creating a with int a . Then you are "NOT" saving the return value of scanf anywhere. That means from scanf , any value you enter is read into a . And that's it. The return value (for scanf , the return value is the number of input values; in this case we are only entering one value so it's 1) is not being fed to a or any other variable. So a now has the value what you entered earlier from your standard input.

int a; scanf("%d", &a);

In the above code an integer variable is declared and its address is passed to scanf function,because inside scamf function the value of a get modified.So in order to reflect the change in the main function you have to pass the address. scanf function reads input from the standard input stream stdin and the value of a will be changed to that.

int a = scanf("%d", &a);

In this piece of code also the working of scanf is similar.But after scanf function,it's return value is assigned to a. scanf function 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.so here the value of a will be 1 or zero.

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