Reputation: 303
I'm attempting exercise 1-8 in the K&R book but having an issue with the amount of newlines being found:
Write a program to count blanks, tabs and newlines.
#include <stdio.h>
main()
{
int c, nl, tabs, blanks;
nl, tabs, blanks = 0;
while ((c = getchar()) != EOF)
{
if (c == '\n')
++nl;
printf("%d\n", nl);
if (c == ' ')
++blanks;
if (c == '\t')
++tabs;
}
printf("\n Blanks: %d\nNewlines: %d\nTabs: %d\n\n", blanks, nl, tabs);
}
I run the program on itself and the output I receive is:
Blanks: 32
Newlines: -1216989677
Tabs: 25
Why is this happening? My first thought was that it could be the minimum possible number of an integer but I checked and I don't believe its that.
Upvotes: 2
Views: 189
Reputation: 45654
You did not initialize nl
and tabs
, so your program has undefined behavior.
nl, tabs, blanks = 0;
only initializes blanks
. It should be
nl = tabs = blanks = 0;
There's one more error: Neither programmer intent nor indentation defines blocks, only curly braces {}
do:
if (c == '\n')
++nl;
printf("%d\n", nl);
I corrected the indentation of the block to make the error obvious. Not quite what you wanted, so use curly braces to group the two statements as one block.
Anyway, consider writing C89 without deprecated compatibility features or even better C11.
That means you have to provide proper prototypes. Possible ones for main
:
int main(void)
int main(int argc, char *argv[])
Also, enable more warnings, and strive for warning-free compilation: -Wall -Wextra
Doing so (including reading and acting on the warnings) will help you identify and correct many errors the easy way.
Upvotes: 3
Reputation: 8020
nl = tabs = blanks = 0;
Compile with -Wall and you'll see the error:
cc -Wall -c a.c
(...)
a.c:4:4: warning: left-hand operand of comma expression has no effect [-Wunused-value]
a.c:4:7: warning: left-hand operand of comma expression has no effect [-Wunused-value]
Upvotes: 3