Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Chapter 6: Exploring Conditional Program Flow

Not only do the values of variables change when a program runs but the flow of execution can also change through a program. The order of statement execution can be altered depending upon the results of conditional expressions. In a conditional program flow, there is one mandatory branch and one optional branch. If the condition is met, the first branch, or path, will be taken; if not, the second path will be taken.

We can illustrate such a branching with the following simple example:

Is today Saturday?

If so, do the laundry.

Else, go for a walk.

In this conditional statement, we are instructed to do the laundry if today is Saturday. For the remaining days that are not Saturday, we are instructed to go for a walk.

This is a simple conditional statement; it has a single conditional expression, a single mandatory branch, and a single optional branch.

The following topics will be covered in this chapter:

  • Understanding...

Technical requirements

As detailed in the Technical requirements section of Chapter 1, Running Hello, World!, continue to use the tools you have chosen.

The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition/tree/main/Chapter06.

Understanding conditional expressions

We have seen how execution progresses from one statement to the next with simple statements. We have also seen how program execution can be diverted or redirected via a function call; after executing the function body, it returns to the place of the function call and continues execution. We are now going to see how the flow of execution can change and how statements can be executed or skipped with some of C's complex statements.

Execution flow will be determined by the result of evaluating conditional expressions, which we learned about in the previous chapter. Conditional expressions can be either simple or complex. Complex conditional statements should be clear and unambiguous. If they cannot be made clear and unambiguous, they should be reworked to be less complex. However, when reworking their results in more awkward code, the complex conditional expression should be thoroughly commented. Careful consideration should be given to the...

Introducing the if()… else… complex statement

if()… else… is a complex statement that can have two forms – a simple form where the if()… part is present, and a complete form where both the if()… and else… parts are present.

In the if()… else… complex statement, either the true path or the false path will be executed. The path that is not taken will be ignored. In the simplest if()… statement where there is no false path, the true path is executed only if the conditional expression is true.

The statement has two syntactical forms, as follows:

  • The simplest form (no false path), as illustrated in the following code snippet:
    if( expression )
      statement1
    statement3         /* next statement to be executed */
  • The complete form (both the true path and the false path), as illustrated in the following code snippet:
    if( expression )  ...

Using a switch()… complex statement

With the if()… else… statement, the conditional expression evaluates to only one of two values – true or false. But what if we had a single result that could have multiple values, with each value requiring a different bit of code execution?

For this, we have the switch()… statement. This statement evaluates an expression to a single result and selects a pathway where the result matches the known values that we care about.

The syntax of the switch()… statement is as follows:

switch( expression )  {
  case constant-1 :    statement-1
  case constant-2 :    statement-2
  …
  case constant-n :    statement-n
  default :            statement-default
}

Here, the expression evaluates a single result...

Introducing multiple if()… statements

The switch statement tests a single value. Could we have done this another way? Yes – with the if()… else if()… else if()… else… construct. We could have written the calc() function using multiple if()… else… statements, in this way:

double calc( double operand1 , double operand2 , char operator )  {
  double result = 0.0;
 
  printf( "%g %c %g = " , operand1 , operator , operand2 );
  if( operator == '+' )
      result = operand1 + operand2;
  else if( operator == '-' )
      result = operand1 - operand2;
  else if( operator == '*' )
      result = operand1 * operand2;
  else if( operator ==  '/'
      if( operand2...

Using nested if()… else… statements

Sometimes, we can make the logic of if()… else… statements clearer by nesting if()… else… statements within either one or both clauses of the if()… else… statements.

In our isLeap() example, someone new to the intricacies of Gregorian calendar development and the subtleties of a century leap year calculation might have to pause and wonder a bit about our if/else fall-through logic. Actually, this case is pretty simple; much more tangled examples of such logic can be found. Nonetheless, we can make our logic a bit clearer by nesting an if()… else statement within one of the if()… else… clauses.

Copy leapYear2.c to leapYear3.c, which we will now modify. Our isLeap() function now looks like this:

bool isLeapYear( int year )  {
  bool isLeap = false;
    // Gregorian calendar leap year calculation.
  ...

Summary

From this chapter, we learned that we can not only alter program flow with function calls but also execute or omit program statements through the use of conditional statements. The if()… else… statement has a much wider variety of forms and uses. The switch()… statement operates on a single value, comparing it to the desired set of possible constant values and executing the pathway that matches the constant value. if()… else… statements can be chained into longer sequences to mimic the switch()… statement and to provide a richer set of conditions than possible with switch()…. Also, if()… else… statements can be nested in one or both clauses to either make the purpose of that branch clear or the condition for each pathway less complex.

In these conditional statements, execution remains straightforward, from top to bottom, where only specific parts of the statement are executed. In the next chapter, we'll...

Questions

  1. Are both statements of an if()… else... statement executed?
  2. Can you replace every if()… statement with a switch()… statement?
  3. Can you replace every switch()… statement with a complex if()… statement?
  4. How do you avoid the dangling else problem?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay