ch3-Pitfall (Assignment and equivalence)

Chapter_3     Exercise_3-14     Comma SimpleCast     Exercise_3-15







Pitfall     TCP1, p. 179  (pitfall.c,  Pitfall.cpp)




pitfall.c         download


#include <stdio.h> // for printf()
#include <unistd.h> // for sleep()

int main()
{
int a = 1, b = 1;

while (a == b) // correct
{
printf("a = %d, b = %d\n", a, b);
b++; sleep(1); // pause for 1 second
}
printf("Out of while1\n");
while (a = b) // instead of while (a == b)
{ // exits when b == 0
printf("a = %d, b = %d\n", a, b);
b--; sleep(1); // pause for 1 second
}
printf("Out of while2\n");
while (a = b) // instead of while (a == b)
{ // exits immediately as b == 0
printf("a = %d, b = %d\n", a, b); // never gets here
b++; sleep(1); // pause for 1 second
}
printf("Out of while3\n");
b++; // b = 1;
while (a = b) // instead of while (a == b)
{ // starts with b == 1
printf("a = %d, b = %d\n", a, b);
b++; sleep(1); // pause for 1 second
} // never exits while4
printf("Out of while4\n"); // never gets here

return 0;
}
/*
gcc pitfall.c -o pitfall
./pitfall
a = 1, b = 1
Out of while1
a = 2, b = 2
a = 1, b = 1
Out of while2
Out of while3
a = 1, b = 1
a = 2, b = 2
a = 3, b = 3
a = 4, b = 4
a = 5, b = 5
a = 6, b = 6
a = 7, b = 7
a = 8, b = 8
^C // Ctrl^C
*/











Pitfall.cpp         download


#include <cstdio> // for printf()
#include <unistd.h> // for sleep()

int main()
{
int a = 1, b = 1;

while (a == b) // correct
{
printf("a = %d, b = %d\n", a, b);
b++; sleep(1); // pause for 1 second
}
printf("Out of while1\n");
while (a = b) // instead of while (a == b)
{ // exits when b == 0
printf("a = %d, b = %d\n", a, b);
b--; sleep(1); // pause for 1 second
}
printf("Out of while2\n");
while (a = b) // instead of while (a == b)
{ // exits immediately as b == 0
printf("a = %d, b = %d\n", a, b); // never gets here
b++; sleep(1); // pause for 1 second
}
printf("Out of while3\n");
b++; // b = 1;
while (a = b) // instead of while (a == b)
{ // starts with b == 1
printf("a = %d, b = %d\n", a, b);
b++; sleep(1); // pause for 1 second
} // never exits while4
printf("Out of while4\n"); // never gets here

return 0;
}
/*
g++ Pitfall.cpp -o Pitfall
./Pitfall
a = 1, b = 1
Out of while1
a = 2, b = 2
a = 1, b = 1
Out of while2
Out of while3
a = 1, b = 1
a = 2, b = 2
a = 3, b = 3
a = 4, b = 4
a = 5, b = 5
a = 6, b = 6
a = 7, b = 7
a = 8, b = 8
^C // Ctrl^C
*/





Note:  See also unistd.h on Wikipedia, cpp-sleep on SoftwareTestingHelp, and why_not_cunistd on StackOverflow.









Chapter_3     Exercise_3-14     Comma BACK_TO_TOP SimpleCast     Exercise_3-15



Comments

Popular posts from this blog

Contents