ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Controlling program flow in C using if and switch

Updated on April 12, 2011

In this hub I'll be showing you how you can execute or not execute statements based on some conditions. We'll be using the keywords "if" and "switch" to achieve this.

This hub is part of a series I'm doing regarding C programming in Linux. If you haven't already, please do check it out so you'd know the full coverage. You'll also find direct links there to the other topics.

Some notes about C statements

To recall, statements in C are any combination of literals, identifiers, keywords and symbols that achieve something. C uses the semi-colon to separate statements, although it functions more like a "terminator" rather than a separator.

Multiple statements can be grouped together using the curly brackets "{" and "}"; this is known as a "statement block".

The statements in a C program are executed from top to bottom. You can also put multiple statements in one line and in this case, the statements will be executed from left to right.

You'll see below that with the use of conditional statements, you can prevent some statements from being executed under certain conditions.

if statement

The keyword if has the following usage specification ("syntax"):

if ( expression )

statement ;

The statement immediately following the "if statement" will be executed only if the expression in the "if statement" evaluates to a non-zero value. Like for example:

if (2 + 5)

x = x + 12;

The assignment statement "x =" above will be executed since the expression "2 + 5" evaluates to "7" which is not zero. If the expression evaluates to zero, then the statement will not be executed.

If there are more than one statement that you'd like to be affected by the "if statement", then you will need to put the statements into a block. Like this:

if(x > 3)
{
   x *= 3;
   y = x + 5;
}

if-else statement

In addition to the "if statement", you can also use the keyword "else" in order to create an alternative code block to be executed if the expression in the "if statement" is false. Please look at the example below:

if (x > 3)
   x = x * 2;
else
   x = x * 5;

As before, if you like to effect the "else" statement to multiple statements, you'll need to put them into a block. Like for example the code below:

if (x > 4)
   x *= 4;
else {
   x *= 3;
   y = x + 2;
   z = y * (x + 1);
}

if-else-if

Another popular use of the "if statement" is to string or chain them together in order to test various conditions, like the code below:

if (a == 1)
   y = x * 2;
else if (a == 2)
   y = x * 4;
else if (a >= 3)
   y = x + (b * 5);
else
   y = 0;

The "if-else" statement above will be evaluated starting from the top-most "if" statement. If the expression evaluates to 0 ("false"), then the next "else if" will be evaluated. If still it results to false, the next "else if" will then be evaluated and so on and so forth.

If one of the "if" statements above results to non-zero ("true"), then the statement next to it will be performed and all the other "else if" statements are then skipped.

In other words, looking at our example above, if the first "if statement evaluates to false, then let's say the second "else if" ("else if (a == 2)") evaluates to a non-zero value, which means "true", the statement "y = x * 4" will be performed then the next "else if" and the "else" statements will not be evaluated at all.

Note that multiple statements inside the "if" or "else" will need the curly brackets as described above.

switch statement

The "switch" statement is used to check for equality. It can only do integer comparison and doesn't support ranges like "less than" or "greater than". It is used in conjunction with the keyword "case".

The "switch-case" statement block has the following syntax:

switch (expression)
{
   case constant-expression:
      statements;
   default:
      statements;
}

The expression in the switch statement will need to yield an integer value. This value is then compared against the value for each of the case statement starting from top to bottom. If a match is found, code execution will begin from there.

It's important to note that the "case" statements only denote where to begin execution given a match. This does not mean that if a match is found in one of the "cases" that the other cases are ignored. To illustrate this, please consider the switch-case statement block below:

switch (a)
{
   case 1:
      y = x * 2;

   case 2:
      y = x * 4;

   case 3:
      y = x + (b * 5);

   default:
      y = 0;
}

The switch statement is testing the expression "a", which is just a variable. In other words, it's testing the value of the variable against the cases below it.

The value next to the "case" keyword is the value tested against the result of the expression in the switch. In other words, "case 1" is like "if ( x == 1 )".

When "a" is equal to the value "1", the first case will match and the code "y = x * 2" will be executed. Now, even though "case 2" did not match, execution will continue and the code "y = x * 4" will also be executed. This behavior is almost always not what you want but can also be useful at times.

break keyword

To prevent the "fall-through" effect we've seen above wherein statements under "case 2" and downwards are executed even though only "case 1" matches, we will use the keyword "break".

When "break" is encountered, execution immediately jumps to the next statement "after" the switch block. So we'll change the switch block above and incorporate some "breaks".

switch (a)
{
   case 1:
      y = x * 2;
      break;

   case 2:
      y = x * 4;
      break;

   case 3:
      y = x + (b * 5);
      break;

   default:
      y = 0;
      break;
}

With the "breaks" added above, only the statements inside the "case" that matches will be executed. This makes it behave similar to the "if-else-if" chain we've seen above.

Note that you don't need curly brackets for the statements for each "case" since technically, the "case" statements are really "labels" (Note the use of colons ":" at the end of a case statement.). The statements inside the "switch" will need to be enclosed with the curly brackets, however, as you can see above.

Finally, there's the "default" case. Sure enough, by the sound of it, this represents a case that will be executed if none of the cases match. Normally this "default" case is placed after the last "case" and being at the bottom, does not require a "break". However, it is advisable that you do put a "break" for the "default" case so that you can move it up quite easily. Also it allows you to easily add a case after it if you need to.

I highly encourage you to experiment with these keywords as they're almost always used in any program. Try re-arranging stuff or breaking the syntax and see what happens. Try using semi-colons instead of colons after the "case" labels and see what happens. It's really helpful to familiarize yourself with the error or warning messages that the compiler spits out. This can save you a lot of time when tracing your program when things go wrong.

Comments

    0 of 8192 characters used
    Post Comment

    • profile imageAUTHOR

      daberill 

      7 years ago

      Appreciate it, Simone! Cheers!

    • Simone Smith profile image

      Simone Haruko Smith 

      7 years ago from San Francisco

      Another excellent guide, daberill! Voted up!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)