Omid
Omid

Reputation: 2667

Variable is treated as uninitialized

In the C code below (that is inspired by an example in K&R), the variable nw is treated as uninitialized:

#include <stdio.h>
#define IN 1
#define OUT 0
main(){

    int c,nl,nw,nc = 0;
    int state = OUT;
    while((c=getchar())!=EOF){
        ++nc;
        if(c=='\n')
            ++nl;
        if(c==' ' || c=='\n' || c=='\t')
            state = OUT;
        else if(state == OUT){
            state = IN;
            ++nw;
        }
    }

    printf( "%d %d %d\n" , nl, nw, nc);
}

For example:

input: one two three
output: 1 796411731 14

The middle figure should have been 3 (nw = number of words)

I don't understand why this happens, given that I explicitly assign a value to it in the beginning.

Upvotes: 1

Views: 80

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

I don't understand why this happens, given that I explicitly assign a value to it in the beginning.

You do not assign the value to nw: nc is the only one assigned.

Unlike array initialization, where you could assign zeros to multiple elements by omitting them from the initializer, scalar variables must all be initialized separately:

int c, nl = 0, nw = 0, nc = 0;

Note that you do not need to initialize c, because it is assigned unconditionally in the loop header.

Upvotes: 3

James M
James M

Reputation: 16718

This line:

int c,nl,nw,nc = 0;

Doesn't do what you think it does. Only nc is set to 0.

If you want to initialize the others as well, you have to do so explicitly:

int c = 0, nl = 0, nw = 0, nc = 0; 

Upvotes: 1

Related Questions