Reputation: 51
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.
Upvotes: 3
Views: 120
Reputation: 37954
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)
Upvotes: 12
Reputation: 53026
b
is uinintiaized this expression is wrong
b, t, nl = 0, 0, 0;
it only initializes nl
, it should be
b = t = nl = 0;
Upvotes: 3
Reputation: 3377
Those are garbage values. You need to assign the variables b
, t
, and nl
to 0 individually.
Upvotes: 2
Reputation: 727047
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.
Upvotes: 2