Chapter 3 Notes

Notes on Section 3.1


  • Boolean Expression


  • Take note of the precedence rules on p. 113

  • Be careful when mixing arithmetic and Boolean connectives. C++ is happy to treat numbers are Boolean values and vice versa, but it might not be the way that you want it to happen. All numbers except 0 are treated as true, while 0 is treated as false. This can trip you up in an expression like !value>5. The way C++ processes this is to first apply the ! (the "not" operator) to value. If value was anything other than 0, value is considered true, so value would evaluate to false. But now we want to ask "Is false > 5?" To make sense of this, C++ converts false back to a number (in this case, 0), and asks "Is 0 > 5?" The answer, of course, is "no", so !value>5 evaluates to false for any non-zero value of "value". (It also evaluates to false if value is zero, so !value>5 turns out to be a fancy way of saying "false".

Notes on Section 3.2 and 3.3


  • Nested if-else statement

  • Multiway if-else statement

  • Controlling expression


  • We'll assume that "size" is a character variable which has been given a value already.

	case 's':
	case 'S':
	  cout << "You want more than that, don't you?\n";
	  size = 'M';
	case 'm':
	case 'M':
	  cout << "A large is only $0.30 more!\n";
	  size = 'L';
	case 'l':
	case 'L':
	  cout << "You are clearly a person of taste.\n";
	  cout << "I did not understand you, but I will\n"
		       << "assume that you wanted a large.\n";
		  size = 'L';

  • We will assume that n is an integer which has already been given some value.

int factorial=1
for(int i=1; i <= n; i++)
	factorial = factorial * i;	


  • When you are nesting or creating multiway if-else statements, braces are your friends.

  • Do not follow standard indenting for multiway or deeply-nested if-else statements. You get nested too deep too fast. See the first few pages of this section for examples.

  • Don't forget the break statements in switch constructions! You can end up executing the commands corresponding to several alternatives you didn't want.

  • It is good practice to include a default option in switch constructions.

  • A break command may be used to terminate a loop abruptly.

  • If you have a loop running inside another loop, a break command exits the inner loop, not the larger one that the inner one was a part of.

Topic revision: r1 - 2015-09-10 - JimSkon
This site is powered by the TWiki collaboration platformCopyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback