Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering

Code Flow Control in C Language

By Ajish Alfred

 

1)Introduction
A programmer can control code flow in a C code using several techniques. Before start coding one should have an idea about the code flow for that particular code. Code flow is purely the logic required for the program. The programmer converts the logic into C code, and he may use the code flow control techniques available in the C during the process.
 
I hope this tutorial will give you a solid idea about the code flow control. The examples actually shows how can you make use of the conditions, loops etc.
 
2)   Conditional branching
In conditional branching, a decision is made to direct the code flow through any one of code blocks based on a condition check
 
2.1)   If else
If else syntax:

If ( condition )
{
Code block for condition TRUE
}
else
{
Code block for condition FALSE
}

 

If else code flow: 

Flowchart showing Operation of If-Else Statement

Fig. 1: Flowchart showing Operation of If-Else Statement 

If the condition is true code block 1 will get executed, otherwise code block 2 will get executed.
 
If else examples:
C_2.1.1 :  Simple if else

int main ()
{
 
char *name = “sachin”;
if ( name == “sachin” )
write ( 0, “ngreat cricketern”, 17 );
else
write ( 0, “ndont known”, 11 );
}
 
Output:
great cricketer
 
C_2.1.2 : Else block not necessary

int main ()
{
char *name = “sachin”;
 
if ( name == “sachin” )
 
write ( 0, “ngreat cricketern”, 17 ); else;
}
 
Output:
great cricketer
 
C_2.1.3 : Nested if else

#include <stdio.h>
 
int main ()
{
char *name = “Emma Watson”;
 
if ( name == “sachin” )
{
 
printf ( “ngreat cricketern” ); printf ( ” true indiann” );
}
else if ( name == “Jackie Chan” )
{
printf ( “ngreat actor” );
printf ( ” great fight mastern” );
}
 
else if ( name == “A R Rehman” ) printf ( “ngreat musiciann” );
 
else if ( name == “Emma Watson” ) printf ( “nHarry Porter Girln” );
else
printf ( “nI dont know whon” );
}
 
Output:
Harry Porter Girl
 
2.2) Using conditional operator
The code flow can be controlled by using the conditional operator also.
 
Syntax for using conditional operator:
( condition ) ? ( code block for condition TRUE ) : ( code block for condition FALSE )
 
Conditional operator examples :
C_2.2.1 : Code equivalent to C_2.1.1

int main ()
{
char *name = “sachin”;
 
( name == “sachin” ) ? write ( 0, “ngreat cricketern”, 17 ) : write ( 0, “ndont known”, 11 );
}
 

Switch Case

 

2.3) Switch

Switch is actually a very handy tool to switch the code flow into a block of code which satisfies the condition check. It is a neat and easy way preferred over the nested if else coding. It also improves the readability of your code.
 
Switch syntax:

witch ( expression that can be reduced to an integer )
{
case value1 :
code block for the expression and value1 matching;
break;
 
case value2 :
code block for the expression and value2 matching;
break;
 
default :
code block if none of the values matches with the expression;
}
 
Simplified code flow:
Flowchart showing Operation of Switch Statement
Fig. 2: Flowchart showing Operation of Switch Statement
 
In the above diagram if the condition 3 is true then code block 3 will get executed. Suppose when both conditions 2 and condition 3 are true, in such a case only the condition 2 will get executed. This is explained by the following code flow.
 
Actual code flow of switch:
Flowchart showing Actual Operation of Switch Statement
Fig. 3: Flowchart showing Actual Operation of Switch Statement
If condition 1 is not true, then condition 2 will get evaluated, otherwise executes code block 1 and exits. If none of the conditions are true then default code block will get executed.
 
Make sure that you don’t have multiple code blocks which satisfy the condition check. If you have more than on code block which can satisfy the condition check, the code block which is written first or whose condition is checked first will only get executed and the code flow returns to the statements after switch block.
 
Switch examples :
C_2.3.1 : Simple switch
 

#include <stdio.h>
 
int main ()
{
int name = 1;
 
switch ( name )
{
case 1:
 
printf ( “ngreat cricketern” ); printf ( “true indiann” ); break;
 
case 2:
 
printf ( “ngreat actorn” ); printf ( “great fight mastern” ); break;
 
case 3:
 
printf ( “ngreat musiciann” ); break;
 
case 4:
 
printf ( “nHarry Porter Girln” ); break;
 
default:
printf ( “nI dont know whon” );
}
}
 
Output:
great cricketer

true indian
 
C_2.3.2 : Function call in switch

#include <stdio.h>
 
int func ( int i );
 
int main ()
{
int i = 2;
 
switch ( func ( i ) )
{
case 1:
printf ( “ncase 1 truen” ); break;
case 2:
printf ( “ncase 2 truen” ); break;
}
}
 
int func ( int i )
{
return i;
}
 
Output: case 2 true
 
 
 

Loops: While Loop

 

3)   Loops

Loops are basically a mechanism provided in C coding, which will execute a block of code continuously until a condition fails.
 
3.1) While loop
It is the simplest loop in the C coding. Loop continues until the condition fails.
 
While loop syntax:
while ( condition )
{
   Code block
}
 
While loop code flow:
Flowchart showing Operation of While Loop
Fig. 4: Flowchart showing Operation of While Loop 
While loop examples:
C_3.1.1 : Simple while loop

#include <stdio.h>
int main ()
{
int i = 0;
while ( i < 10 )
{
printf ( ” %d”, i ); i ++;
}
}
Output:
0 1 2 3 4 5 6 7 8 9
 
C_3.1.2 : Infinite while loop

#include <stdio.h>
int main ()
{
while ( 1 ) // condition is always true
printf ( “nI won’t stop” );
}
 
The above code is an example of infinite loop. It will execute infinitely printing “I won’t stop”.
 
C_3.1.3 : Wait statement using while loop

#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen ( “new.txt”, “r” );
while ( ‘A’ != fgetc ( fp ) ); // wait till letter ‘A’ is reached while reading the file
printf ( “nLetter ‘A’ foundn” );
}
 

Do While Loop

 

3.2) Do while loop

In contrast to the while loop, the code block is executed before checking the condition. Thus in do while loop, the code block is executed at least once.
 
Do while loop syntax
do
{
   Code block
}
 while ( condition )

 

Do while code flow:

Flowchart showing Operation of Do-While Loop

 

Fig. 5: Flowchart showing Operation of Do-While Loop 

Do while examples
C_3.2.1 : Simple do while loop

#include <stdio.h>
int main ()
{
int i = 0;
do
{
printf ( “n%dn”, i ); i ++;
}
while ( i < 10 );
}
 
Output:
0 1 2 3 4 5 6 7 8 9
 
C_3.2.2 : Code block executed at least once

#include <stdio.h>
int main ()
{
int i = 10;
do
{
printf ( “nEntered the loop oncen” );
}
while ( i < 10 );
}
 
Output:
Entered the loop once
 

For Loop

 

3.3) For loop

For loop consist of three sections:
–          Initialization
–          Condition check
–          Code block
–          Updating
 
For loop code Flow:
Flowchart showing Operation of For Loop
Fig. 6: Flowchart showing Operation of For Loop
 
For loop syntax:
for ( initialization; condition; update )
{
  Code block
}
 
Executing the code block continues till the condition fails.
 
For loop examples:
C_3.3.1 : Simple for loop

#include <stdio.h>
int main ()
{
int i;
for ( i = 0; i < 3; i ++ )
{
printf ( “nEntered the loopn” ); printf ( “nNow value of i = %dn”, i );
}
}
 
Output:
Entered the loop
Now value of i = 0
Entered the loop
Now value of i = 1
Entered the loop
Now value of i = 2
 
C_3.3.2 :  Infinite for loop

#include <stdio.h>
int main ()
{
for ( ; 1; )
printf ( “nI won’t stopn” );
}
 
C_3.3.3 : Waiting using for loop

#include <stdio.h>
int main ()
{
int i;
char *str = “xxxxxxxxxxxxxxxxyyyyyyyyAzzzzzzzzzz”;
for ( i = 0; ‘A’ != * ( str + i ); i ++ );
printf ( “nThe current Letter is : %cn”, * ( str + i ) );
}
printf () is not executed till the ( str + i ) is pointed towards letter ‘A’ in the string.
 
C_3.3.4 : Generating a delay using for loop

#include <stdio.h>
int main ()
{
int i = 1000000000;
for ( ; i; i — );
printf ( “nsorry for the delayn” );
}
 
In the above code, the printf () is delayed by around 4 seconds.
 

Function Calls

 

4)   Function calls

Code flow is switched to a function when it is called. Then the statements in the called function will get executed. The code flow is switched back to the calling code block as the called function returns or exits.
 
Consider the following code
C_4.1

#include <stdio.h>
int sqr_sum ( int x, int y ); int sqr ( int x );
int main ()
{
int x;
x = sqr_sum ( 2, 5 );
printf ( “nThe square of sum of two numbers = %dn”, x ); return 0;
}
 
int sqr_sum ( int x, int y )
{
int z;
z = sqr ( x + y ); return z;
}
 
int sqr ( int x )
{
return x * x;
}
 

 

The code flow for the code C_4.1 looks somewhat like this
Flowchart showing Operation of Example Code
Fig. 7: Flowchart showing Operation of Example Code
Here printf () is assumed to be not made inline by the compiler.

Inline Functions

5)   Inline Functions

As we have seen in the above example, a function call is associated with a calling sequence and a return sequence. In the process lot of data has to be moved in and out of the stack. This affects the performance of the code, or simply the code will become slower.
 
To avoid the delay we can use the function specifier “inline” for small functions. Inline substitutes the function call with the modified code of the function itself, so that the compiler can execute sequentially without bothering the calling sequence or return sequence.

 

The only disadvantage is that the executable code size changes, and sometimes increases.

 

We can use inline in the code C_4.1 as given below
C_5.1

#include <stdio.h>
inline int sqr_sum ( int x, int y ); inline int sqr ( int x );
int main ()
{
int x;
x = sqr_sum ( 2, 5 );
printf ( “nThe square of sum of two numbers = %dn”, x ); return 0;
}
 
inline int sqr_sum ( int x, int y )
{
int z;
z = sqr ( x + y ); return z;
}
 
inline int sqr ( int x )
{
return x * x;
}
The executable code size increases when there is multiple calls to the inlined function, as the code of the inlined function has to be duplicated many times in the executable file.
 
Rules for inlining
–     Use inline only when better performance is guaranteed
–     All functions can be inlined except main ()
–     Never use static variables in a function which is defined inline
–     Can’t use inline in recursive functions
–     Prefer inline instead of macros.
 
It is actually very difficult make a comparison on either the performance or code size of a code using inlined functions with the same code in which the functions are not inline, because most of the compilers while optimizing the code, make functions inline or not.

Conclusion

6)   Conclusion

Before you write a single line of code in C, you should have a complete code flow diagram of the particular program with you. If you have a solid idea about the basic code flow of conditional branching, loops and flow control, you can easily extract those blocks from the code flow diagram of your program. Then you know where to use loops, conditions, which all parts to be made sub functions, where to use function calls etc.
 
Note : I’ve used gcc 4.1.2 in Linux to compile the codes presented in this article. If you have any issues with the information in this article please let me know.

 


Filed Under: Tutorials
Tagged With: c language, code flow, language
 

Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


Featured Tutorials

  • Introduction to Brain Waves & its Types (Part 1/13)
  • Understanding NeuroSky EEG Chip in Detail (Part 2/13)
  • Performing Experiments with Brainwaves (Part 3/13)
  • Amplification of EEG Signal and Interfacing with Arduino (Part 4/13)
  • Controlling Led brightness using Meditation and attention level (Part 5/13)
  • Control Motor’s Speed using Meditation and Attention Level of Brain (Part 6/13)

Stay Up To Date

Newsletter Signup

Sign up and receive our weekly newsletter for latest Tech articles, Electronics Projects, Tutorial series and other insightful tech content.

EE Training Center Classrooms

EE Classrooms

Recent Articles

  • EdgeLock A5000 Secure Authenticator
  • How to interface a DS18B20 temperature sensor with MicroPython’s Onewire driver
  • Introduction to Brain Waves & its Types (Part 1/13)
  • An Embedded Developer’s Perspective on IOT (Internet of Things)
  • Understanding NeuroSky EEG Chip in Detail (Part 2/13)

Most Popular

5G 555 timer circuit 8051 ai Arduino atmega16 automotive avr bluetooth dc motor display Electronic Part Electronic Parts Fujitsu ic infineontechnologies integratedcircuit Intel IoT ir lcd led maximintegratedproducts microchip microchiptechnology Microchip Technology microcontroller microcontrollers mosfet motor powermanagement Raspberry Pi remote renesaselectronics renesaselectronicscorporation Research samsung semiconductor sensor software STMicroelectronics switch Technology vishayintertechnology wireless

RSS EDABOARD.com Discussions

  • Need help to choose accelerometer
  • Pic 16f877A Hex file
  • 7 segment display connections
  • finding attenuation coefficient in CST
  • Effect of variable gain amplifier and LNA on the input RF signal's phase

RSS Electro-Tech-Online.com Discussions

  • How to designing a battery charging indicator circuit for 18650 battery pack
  • NOR gate oscillator in LTspice not working
  • ICM7555 IC duty cycle limit at high frequency?
  • I've DESTROYED 3 piezo buttons :((((
  • led doorbell switch
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • About Us
  • Contact Us
  • Advertise

Copyright © 2022 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy | Advertising | About Us

Search Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering