The definition of scanf()
says nothing about what it will do to the value of arguments that cannot be assigned, but invariably in practice, it leaves them untouched.
In this case both n
and i
are unitialised and may contain any value - in your case n
happened to contain zero at the moment you tried it, but that is not a given - it is undefined. The C runtime is not required to initialise variables with auto
storage class (local, non-static
) to zero.
int n = 0;
int i = 0;
Note also that sscanf()
returns the number of format specifiers that result in a successful assignment, so you can for example:
while( scanf("%d",&n) == 0 )
{
// wait until valid input
}
This is strictly safer than relying only initialisation of a "default" value because scanf()
strictly makes no guarantees that it will not modify an argument in any case - it would only be an unusual implementation that did so. Also in practice you would normally want to handle erroneous input one way or another rather then simply ignore it and use a default. A safe and unambiguous way of providing a default if required is:
if( scanf("%d",&n) == 0 )
{
n = 0 ;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…