Reputation: 13
#include <stdio.h>
#define YES 1
#define NO 0
int main()
{
int c, nl, nw, nc, tab;
nl = 0;
nw = 0;
nc = 0;
tab = YES;
while ((c = getchar()) != EOF)
{
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\t' || c == '\n')
tab = YES;
else if (tab == YES)
{
tab = NO;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
This code here counts new lines, words and characters in the input. What I do not understand is that when you swap YES for NO and NO for YES, you still receive the same answer. What is the explanation behind this?
#include <stdio.h>
#define YES 1
#define NO 0
int main()
{
int c, nl, nw, nc, tab;
nl = 0;
nw = 0;
nc = 0;
tab = NO;
while ((c = getchar()) != EOF)
{
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\t' || c == '\n')
tab = NO;
else if (tab == NO)
{
tab = YES;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
This is the second version that still produces same output
Upvotes: 0
Views: 61
Reputation: 12708
You have just changed the labels in your program, but you have not changed the logic on it, so it is normal your program has changed nothing in its behaviour.
Assume you have a program that uses the constant PI
to represent the infamous number 3.1415926535897932
, and after testing the program (e.g. to calculate the longitude of a circunference of radius D
) you decide to rename the constant name from PI
to THE_INFAMOUS_CONSTANT_PI
, and you change any appearance of the constant name PI
to the new name. Have you changed something in the logic of your program? simply not. You even could not guess that the variable name has been changed because the compiler, in the compilation process, uses all references to that name and substitutes all by the infamous number. Once done that, the compiler drops the name and there's no trace on how was the variable named in the program.
Had you written:
else if (tab)
in your code. instead of:
else if (tab == NO)
then the logic would have depended on the value assigned to NO
. But you don't even use the state variable as a boolean, you use it as a pure enumerated value, so none in the logic has changed. And the program behaves exactly as before the change. If you had changed the values of the two constants to 17
and 23
, the logic shouldn't have changed also, only if you had assigned the same value to both constants, then you would have never changed state, and the count of words should drop to 0 (or 1, depending if the file has a non spacing character)
Upvotes: 0
Reputation: 154562
tab
is used as a flag in one of 2 states. It makes little difference if the 2 states are 0,1 or 1,0 or red,green or 1.23/4.56. Code is only testing for equality, not value.
tab = YES;
primes later code for the beginning of a word and if (tab == YES)
acts on that.
tab = NO;
disables word count.
Upvotes: 1