3

I'm trying to make a C program that will count and print the number of tabs, spaces, and lines input by the user. The problem is that when it prints those numbers, they are wildly off. Here is my program code:

int c, b, t, nl;
b, t, nl = 0, 0, 0;
while ((c = getchar()) != EOF) 
{
    if (c == '\b') 
        b++;
    if (c == '\t') 
        t++;
    if (c == '\n') 
        nl++;
}
printf("b=%d t=%d nl=%d\n", b, t, nl);

When I input some data from the terminal (3 lines, one space, one tab), the result is b=1899313536, t=32768, and nl=3.

1
  • 1
    BTW: Good proper type of int c rather than char c. Commented Jan 1, 2015 at 22:59

4 Answers 4

12

The problem is with this line:

b, t, nl = 0, 0, 0;

It uses comma operator on both sides of assignment, hence only nl is intialized with zero. There are no side-effects for evaluation of b, t on left side* and two trailing zeros on the right side of = operator (notice that assignment has higher precedence, than comma operator).

Change it to:

b = t = nl = 0;

which effectively means (as = operator has right associativity):

b = (t = (nl = 0));

*unless b or t are declared as volatile (as reading of such object is counted as side-effect by C Standard)

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

Comments

3

b is uinintiaized this expression is wrong

b, t, nl = 0, 0, 0;

it only initializes nl, it should be

b = t = nl = 0;

Comments

2

Unlike Lua or several other languages that let you assign multiple variables in a single statement

v1, v2, v3 = c1, c2, c3; // <<== This is not a valid C syntax.

C requires you to assign them individually:

b = 0;
t = 0;
nl = 0;

Better yet, you could initialize the variables at the time of declaration, like this:

int c, b=0, t=0, nl=0;

The reason why your current code compiles, though, is a little curious: it treats commas in your code as comma operators, which are legal on both sides of the assignment.

1 Comment

The comment about why this compiles is useful but might be slightly improved by exhibiting the equivalent line without them.
2

Those are garbage values. You need to assign the variables b, t, and nl to 0 individually.

Comments

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.