Chapter 7: Flow control and Functions
C Language(Basics & Fundamentals) - Chapter 7

Chapter 7: Flow control and Functions


PART 1: FLOW CONTROL


Flow control statements determine the next statement to execute. In this sense, the statements if-else, if, switch, while, for, and do are flow control statements. However, these statements do not allow us to determine in an arbitrary way which is the next statement to be executed. Instead they structure the program, and the execution flow is determined by the structure of the program.

In the C language, statements can be written only within the body of a function; more specifically, only within compound statements. The normal flow of control among statements is sequential, proceeding from one statement to the next. However, as we shall see, most of the statements in C are designed to alter this sequential flow so that algorithms of arbitrary complexity can be implemented. This is done with statements that control whether or not other statements execute and, if so, how many times.

Control Structures are just a way to specify flow of control in programs. Any algorithm or program can be clearer and understood if they use self-contained modules called as logic or control structures. It basically analyzes and chooses in which direction a program flows based on certain parameters or conditions.

There are three basic types of logic, or flow of control, known as:

  • Sequence logic, or sequential flow
  • Selection logic, or conditional flow
  • Iteration logic, or repetitive flow

?

Sequential Logic (Sequential Flow):

Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the series of instructions given to the computer. Unless new instructions are given, the modules are executed in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also, implicitly follows the order in which modules are written. Most of the processing, even some complex problems, will generally follow this elementary flow pattern.

?

Selection Logic (Conditional Flow or Branching):

Selection Logic simply involves a number of conditions or parameters which decides one out of several written modules. The structures which use these type of logic are known as Conditional Structures. In simple words this logic decides what actions to take.

For example: if, if else, switch,

?

Iteration Logic (Repetitive Flow or Looping):

The Iteration logic employs a loop which involves a repeat statement followed by a module known as the body of a loop. In simple words this logic decides how many times to take a certain action.

For example: For loop, while loop, do…while


PART 2: FUNCTIONS


  • A function is a set of statements that take inputs, do some specific computation and produces output.
  • The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call the function.
  • You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
  • A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
  • The C standard library provides numerous built-in functions that your program can call. For example, main(), strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.
  • A function can also be referred as a method or a sub-routine or a procedure, etc.

Why do we need functions?

  1. Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to change at one place if we make future changes to the functionality.
  2. Functions make code modular. Consider a big file having many lines of code. It becomes really simple to read and use the code if the code is divided into functions.
  3. Functions provide abstraction. For example, we can use library functions without worrying about their internal working.

Defining a Function

The general form of a function definition in C programming language is as follows

return_type function_name( parameter list ){
??body of the function
}        

A function definition in C programming consists of a function header and a function body.

Here are all the parts of a function:

Return Type ? A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

Function Name ? This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters ? A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Body ? The function body contains a collection of statements that define what the function does.

?

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts:

return_type function_name( parameter list );

For example, the function declaration of max() is as follows,

int max(int num1, int num2);        

Function declaration is also required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

?

Calling a Function

  • While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
  • When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.
  • To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.

While calling a function, there are two ways in which arguments can be passed to a function:

  1. Call by value - This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
  2. Call by reference - This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.

?

Function Arguments

  • If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
  • Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.


Following are some important points about functions in C.

1) Every C program has a function called main() that is called by operating system when a user runs the program.

2) Every function has a return type. If a function doesn’t return any value, then void is used as a return type. Moreover, if the return type of the function is void, we still can use return statement in the body of function definition by not specifying any constant, variable, etc. with it, by only mentioning the ‘return;’ statement which would symbolize the termination of the function as shown below:

void function name(int a)
{
//Function Body
return;?//Function execution would get terminated
}        

3) In C, functions can return any type except arrays and functions. We can get around this limitation by returning pointer to array or pointer to function.

4) Empty parameter list in C means that the parameter list is not specified and function can be called with any parameters. In C, it is not a good idea to declare a function like fun(). To declare a function that can only be called without any parameter, we should use “void fun(void)”. As a side note, in C++, an empty list means a function can only be called without any parameter. In C++, both void fun() and void fun(void) are same.

5) If in a C program, a function is called before its declaration then the C compiler automatically assumes the declaration of that function in the following way:

int function name();        

And in that case, if the return type of that function is different than 'int', compiler would show an error.

?

Main Function:

The main function is a special function. Every C program must contain a function named main. It serves as the entry point for the program. The computer will start running the code from the beginning of the main function. All Predefined and User-defined Functions are called directly or indirectly through the main.

Types of main Function:

1) The first type is – main function without parameters :

// Without Parameters

int main(){
//Function Body
return 0;
}        

2) Second type is main function with parameters :

// With Parameters

int main(int argc, char * const argv[]) {
//Function Body
return 0;
}        

  • The reason for having the parameter option for the main function is to allow input from the command line.
  • When you use the main function with parameters, it saves every group of characters (separated by a space) after the program name as elements in an array named argv.
  • Since the main function has the return type of int, the programmer must always have a return statement in the code. The number that is returned is used to inform the calling program what the result of the program’s execution was. Returning 0 signals that there were no problems.


Some common functions used in C Language:

Functions included in <stdio.h>

printf() – Used to display output on the screen.

scanf() – To take input from the user.

getchar() – To return characters on the screen.

putchar() – To display output as a single character on the screen.

fgets() – To take a line as an input.

puts() – To display a line as an output.

fopen() – To open a file.

fclose() – To close a file.

?

Functions included in <conio.h>

clrscr() – This function is used to clear the output screen.

getch() – It reads character from keyboard

getche() – It reads character from keyboard and echoes to o/p screen

textcolor() – This function is used to change the text color

textbackground() – This function is used to change text background


List of articles from the series:

CH 1) Programming environment

CH 2) Syntax and Semantics

CH 3) Libraries & Header files

CH 4) Preprocessor & Objects

CH 5) Commands & Tokens

CH 6) Declaration & Statements

CH 7) Flow control & Functions

CH 8) Errors & Habits


References:?Wikipedia, CMan(Bell Labs), GeeksforGeeks, guru99 and various other blogs, videos and sites on available internet.

If you find any errors or disinformation in this article, then please inform me.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了