c - Use scanf in if statement -


why output '4' ? , while input 'a'

int main() {  int = 5;   if(scanf("%d",&a))   printf("%d",a+1);   else   printf("%d",a-1);   } 

when type sepcifier %d used function expects valid signed decimal integer number entered. evident symbol 'a' not number input failed.

now question arises: function return in case?

according description of function scanf (the c standard, 7.21.6.4 scanf function):

3 scanf function returns value of macro eof if input failure occurs before first conversion (if any) has completed. otherwise, scanf function returns number of input items assigned, can fewer provided for, or zero, in event of matching failure.

so condition in if statement

if(scanf("%d",&a))   

evaluated 0 (false) , else statement executed.

else   printf("%d",a-1);   

that outputed 4.

take account in general may enter symbol 'a' integers. in case corresponding integer variable must declared unsignedand format specifier of scanf must %x

for example

#include <stdio.h>  int main( void ) {     unsigned int = 5;      if ( scanf( "%x", &a ) )     {               printf( "%u\n", + 1 );     }     else     {         printf( "%u\n", - 1 );     } } 

in case output 11.:) scanf consider symbol 'a' hexadecimal representation of 10.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -