0

when I run the first program, nl (newline) is set to 7ff, and prints out 129.

#include<stdio.h>
// countblanks-tabs-newlinesv1.c
void main()
{
    long int c;
    unsigned char nl, space, tab = 0  ;

    while( ( c = getchar() ) != EOF) 
    {
        if ( c == '\n') 
        {
            nl++;
        }
        if ( c == ' ')
        {
            space++;
        }
        if ( c == '\t')
        {
            tab++;
        }
    }
    printf("input has %d newlines, %d spaces and %d tabs\n", nl, space, tab);


}   

But when I run the second program everything works fine...I think.

Second program

#include<stdio.h>
// countblanks-tabs-newlinesv2.c
void main()
{
    long int c;
    char space, tab ;
    int nl;
    nl = 0;
    space = 0 ;
    tab = 0;

    while( ( c = getchar() ) != EOF) 
    {
        if ( c == '\n') 
        {
            nl++;
        }
        if ( c == ' ')
        {
            space++;
        }
        if ( c == '\t')
        {
            tab++;
        }
    }
    printf("input has %d newlines, %d spaces and %d tabs\n", nl, space, tab);


}   

btw this is exercise 1-8 in The C Programming Language Book

simn7
  • 1

1 Answers1

3

You didn't initialize nl and space to 0 in the first version. They have unpredictable initial values, so you get an unpredictable total.

When you write

unsigned char nl, space, tab = 0  ;

the = 0 initializer only applies to tab, not all the variables. You need to provide an initial value to each of them:

unsigned char nl = 0, space = 0, tab = 0  ;
Barmar
  • 741,623
  • 53
  • 500
  • 612