[TriLUG] a C question

Paul D. Boyle boyle at laue.chem.ncsu.edu
Wed Oct 23 10:20:03 EDT 2002


Tanner Lovelace wrote:
> fav_num is declared as an integer.  You then specify to scanf a %d,
> which stands for a "decimal" number.  Therefore, scanf is looking
> for a decimal number which it converts from the string you entered
> to the end format.  When you enter a string, it tries to convert
> and gets an error.  Since it was looking for a number and didn't
> find one, it just returns 0 which scanf then assigns to fav_num.

This paragraph contains a subtle error.  It is true that in Greg's
code scanf() does return 0 (the prototype for scanf() is more fully:
'int scanf( const char *format, ... )'.  However, returned zero does
not mean that the value of 'fav_num' is modified by being assigned zero.

For proof, consider the behavior of Greg's code with the following
modifications:

#include<stdio.h>

int fav_num = 42;

int main(void)
{
      int n_scanned;

      printf("What is your favorite number?\n");

/* catch the return value of scanf() with 'n_scanned' */
      n_scanned = scanf("%d", &fav_num);
      printf("\n\nYour favorite number is %d\n\n", fav_num);
      printf( "Number of items scanned: %d\n", n_scanned );
      return 0;
}


If you enter text, 'n_scanned' is assigned 0 and fav_num is
still '42'.

Paul


-- 
Paul D. Boyle			    |	boyle at laue.chem.ncsu.edu
Director, X-ray Structural Facility |	phone: (919) 515-7362
Department of Chemistry - Box 8204  |	FAX:   (919) 515-5079
North Carolina State University     |	http://www.xray.ncsu.edu  
Raleigh, NC, 27695-8204



More information about the TriLUG mailing list