简体   繁体   中英

What happens if I pass a variable value instead of a variable reference in scanf?

I have this code:

int a;

scanf("%d", &a);

printf("You entered: %d", a);

which works perfectly fine, but I wondered what would happen if I pass the variable value instead of the variable reference in scanf like scanf("%d", a) .

I don't get an error from the compiler but there is no output either. What is happening here?

In scanf "%d" is expecting a pointer to int meaning a pointer to the address of the variable where the value will be stored, if you pass a you will just be passing int there is no way the value can be stored because scanf won't know where.

Doing this will invoke undefined behavior .

Basically the & is an operator that returns the address of the operand. If you give in scanf the variable a without the &, it will be passed to it by-value, which means scanf will not be able to set its value for you to see. Passing it by-reference - using & actually passes a pointer to a - allows scanf to set it.

scanf expects the argument corresponding to the %d conversion specifier to be the address of an int object (with type int * ). Whatever value a contains will be interpreted as an address 1 .

The behavior on doing this is undefined - the compiler isn't required to issue a diagnostic during translation, and the runtime environment isn't required to throw any kind of exception. Depending on the value contained in a you may get a runtime error, or you may clobber another data object, or your code may work without any apparent errors, or something completely different may happen.


  1. At least on systems where sizeof (int) == sizeof (int *) - for a system like x86_64, that's not the case, so scanf will treat bytes outside of a as part of an address.

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