0

Why does the int variable nl evaluate to 33881 if you call a printf("%d",nl); after this the following line?

nl, nw, nc = 0;

How could it possibly evaluate to any other value than 0 before the loop? I am compiling with gcc from the terminal in a crouton/Ubuntu 12.04LTS environment on my ARM Chromebook, so I don't know if this is a bug in the code or my machine.

#include <stdio.h>

#define IN 1
#define OUT 0

main() {
  int c, nl, nw, nc, state;
  state = OUT;
  nl, nw, nc = 0;
  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);
}

I tried adding another declarative line nl = 0; to force the program to return predictable values, but I still am no closer to understanding this behavior.

1
  • OT: It's ìnt main(void) at least. Commented Feb 22, 2015 at 16:57

2 Answers 2

1

This

nl, nw, nc = 0;

does not initialize nl; if you enable compiler warnings it will tell you that the left operand of the comma operator has no effect, because the , operator ignores all the left operands and keeps the last one. To initialize all the variables at once you need this:

nl = nw = nc = 0;

Since nl is uninitialized, it contains a garbage value; you need to explicitly initialize it.

Compiler warnings would also complain about nl and nw being uninitialized.

Sign up to request clarification or add additional context in comments.

2 Comments

So the evaluation is the "standard" or "placeholder" value assigned to any variable of type int that just hasn't been declared as something else, Thank you. I just feel silly now.
@user134143 no, variables are not initialized when you declare them, it's just that the memory location where they are stored contains something that then is overwritten when you initilize it, it's done that way for performance reasons.
0

The line

nl, nw, nc = 0;

will initialize the variable "nc", but the variables "nl" and "nw" will receive some random number.

To initialize all three you must use

nl = nw = nc = 0;

3 Comments

Would it be a coincidence (as in the memory of where it was allocated was holding "0")if I told you that the nw variable evaluated to 0 as well, only the nl was throwing that strange number,
@user134143 it's nothing but a coincidence.
I think so, because when your program asks the OS to allocate the memory for a variable, for example an int, the OS reserve 16 bits (on most systems) for that variable and these 16 bits can contain any value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.