Monday, February 29, 2016

Use of Functions in C

In C, a function is nothing but a self-contained block of code that can be accessed by specifying its name and providing the appropriate arguments to it from any part of the program. The argument list must be separated by commas. If the function does not require any arguments, then the function name will be followed by the empty parenthesis. The arguments used in the function call are known as actual arguments. The arguments in the first line of function definition are called formal arguments or actual parameters. The actual arguments must be of the same data type as the formal arguments. During the function call, values of actual arguments are copied into the formal arguments
Sometimes functions return values too. In that case, the value returned by the function can be assigned to a variable using assignment operator. Function calls may happen multiple times from different parts of the program and the actual argument may vary. But in all function calls the different arguments must be of the same data type as the formal argument and also the number and order of arguments must be same.
The general form of function prototypes looks like ...
  1. data_type function_name(data_type1 argument1, …, data_typeN argumentN);
and the function call will look like -
  1. function_name(argument1, argument2, , argumentN) ;

Example of a Function in C

A simple program with function call will look like this...
  1. #include<stdio.h>
  2. void print_hello();
  3.  
  4. void main()
  5. {
  6. print_hello();
  7. }
  8.  
  9. void print_hello()
  10. {
  11. printf("Hello world\n");
  12. }
This program just prints "Hello world" on the screen. The line after '#include' directive is called a function prototype. It declares that function 'print_hello' does not return anything and does not take any arguments. The function call is inside the 'main()'. After 'main', there is function definition which defines what the function does.

Placement of the Function

The function prototype should be defined before 'main' function, so that when the functions are called, compiler can decide whether the function exists or not or is on a different file. The function call can be placed in the 'main' function or even in another function body. The function body or definition can be placed before 'main' or after 'main' . If the function definition is placed before the invocation, then there is no need for function prototype.
In case the whole program is divided in multiple files, the function prototypes most likely to be included in the header file (files with '.h' extension). The file from which the function is invoked must include the header file containing the prototype. The function body in that case can be in a source file ('.c') or can be placed inside the header file as well.

Sunday, February 28, 2016

Conditional Compilation pre-processors

There are other C pre-processors like #if, #elif, #else, #endif etc which are used for conditional compilation. If we want to skip over a part of code during compilation, we can use these pre-processors. This is mostly useful when we write code which depends on the operating system. Suppose, some code we have written is not applicable for Windows and only applicable for Linux machines, we can skip the code, when compiling from Windows machine using this pre-processors. The general form of #ifdefis

  1. #ifdef macroname
  2. Statement block;
  3. #endif
The '#ifdef' stands for 'if defined'. It means that if the macro name is already defined somewhere, then the statement block will be included in the source for compilation, otherwise it will be skipped. The #ifdefis accompanied by an #endif statement, which marks the end of statement block. We can use #ifndef, which is applicable when we want to compile part of program if the corresponding macro name is not defined. Like nested if...else , #ifdef also can be combined with #elif and #else. We can use them as given in the below example.

Conditional Compilation Example in C

  1. #ifdef SYSTEM==LINUX
  2. statement block 1;
  3. #elif SYSTEM==WINDOWS
  4. statement block 2;
  5. #else
  6. statement block 3;
  7. #endif

Predefined Macros

Apart from the above mentioned macros, ANCI has a set of predefined macros which can be used for functionalities that's used commonly in application programs. They are explained below.
MacroDescription
__DATE__Gives current date in MMM DD YYYY format
__TIME__Gives current time in HH:MM:SS format
__FILE__Gives the current file name
__LINE__Gives the current line number of source code
__STDC__Gives 1 when the compilation follows ANSI standard

Thursday, February 25, 2016

#pragma Pre-processor Directive

Pragma is used to turn on or off some of compiler/system features. Pragma's operation is system and compiler dependent. So, all pragmas may not work with all the compilers. When pragmas are encountered, the default behaviour of the compiler is overwritten by the options provided by pragmas. One of such pragma is 'pragma startup' and 'pragma exit'. The pragma startup is used to specify function that will be called before main function and pragma exitis used to specify function that would be called just before the program exits. Consider the example program

Pragma Example in C

  1. #include<stdio.h>
  2.  
  3. void function1();
  4. void function2() ;
  5.  
  6. #pragma startup function1
  7. #pragma exit function2
  8.  
  9. void main()
  10. {
  11. printf("In main function");
  12. }
  13.  
  14. void function1()
  15. {
  16. printf("In function1\n");
  17. }
  18.  
  19. void function2()
  20. {
  21. printf("In function2");
  22. }
  23.  
  24. Output:
  25. In function1
  26. In main function
  27. In function2 .

Wednesday, February 24, 2016

C Preprocessor Directives and Macros

C pre-processor directives help us to modify the program text before it is compiled. Basically, C pre-processors directives have the capability of simple text substitution tool, so that you can modify parts of program before it's actually compiled. We've already used few of the C pre-processors in the examples discussed in different chapters of this C programming tutorial. One of them is #include pre-processor directive which includes a header file into the program. Apart from including header files, there are other C pre-processor directives also which allow us to define a constant, write macros etc. C pre-processor comes in handy if you want some part of your code to be compiled depending on some condition. It is also known as conditional compilation.

Macro Definition in C

The macro can be used to define code that would be in-lined to the source code before compilation. The macro can be of two types, object likes (macro without arguments) and function like (macro with arguments or parameterized macros). Object like macro does not take any argument where function type macro resembles a function as it takes arguments like functions.

Example of #undef and #define Macros in C

  1. #include<stdio.h>
  2. #define A 2
  3. void main()
  4. {
  5. printf("First value: %d\n", A);
  6. #undef A
  7. #define A 3
  8. printf("Second value: %d", A);
  9. }
The above program will generate the output as "First value: 2" and in the second line "Second value: 3". At first, we defined the value of 'A' as 2 and, after first 'printf', the'#undef' code will undefine the value of 'A' and the following 'define' statement will define it again with value 3. Please note that all these happens before actual compilation of program

#include pre-processor Directive

We have already used '#include' directive a number of times in different examples discusses so far. This pre-processor is used for file inclusion. Using '#include' pre-processor causes the definition of header file to be included in the source file. That way when we are using functions from different header files, like 'printf', program knows what these functions do. It is also useful for inclusion of the user defined header files as well. There are two ways to write'#include' directive.
  1. #include <header_file.h>
  2. or,
  3. #include "header_file.h"
Both of the above statements include the header file specified as part of it, the only difference is in the search path of the header file. If we use angular brackets (< >), then the header file is searched in the system defined path. In the case of double quotation (" "), the header file will be searched first in the current path, i.e. the path where the source file is. Mainly we use angular brackets when including a system provided header file and double quotes are used when including header files written by the programmer.

Macro Function/Parameterized Macros

The macros we have used until now are without any arguments. Macros can have arguments too, like the functions. Such macro definitions are called parameterized macros. A simple example of parameterized macro definition is given below

Parameterized Macro Example in C

  1. #include<stdio.h>
  2. #define SQUARE(x) (x * x)
  3. void main()
  4. {
  5. int i = 3;
  6. int sq = SQUARE(i);
  7. printf("Square value: %d\n", sq);
  8. }
This program will generate output as "Square value: 9". But there is something different in parameterized macro in comparison with functions in C. Macro definitions are in-lined in the program, which means the definition of the macro 'SQUARE'will be replaced in the program before compilation. So, the statement
  1. int sq = SQUARE(i);
will be replaced by
  1. int sq = (i * i);
The advantage of using the macro is that it does not depend on the type of the arguments and also the macro function is in-lined. It is also a disadvantage of macro. Consider the above macro function 'SQUARE', and we use it in the program as SQUARE( i + 1). We know that value of 'i' is 3 and so the expected output should be 16. But the reality is quite different. As the macro is inlined, SQUARE(i + 1) will be replaced by (i + 1 * i + 1). Now the precedence of operator '+' is lower than '*'. So the statement will be treated as (i + (1 * i ) + 1) and will generate output 7. One way to avoid this, is by using parenthesis in macro, like
  1. #define SQUARE(x) ((x) * (x))
or where we used the macro, like
  1. int sq = SQUARE((i + 1));

Multi-Lined Macros

The macro functions can be multi line statements also. To write multiline macro, each line must be followed by a backslash ("\") except the last line. A multiline macro looks like the following

Multiline Macro Example in C

  1. #define ABC(n)\
  2. for(i = 0; i < n; i++)\
  3. {
  4. printf("%d\n", i);\
  5. }

Tuesday, February 23, 2016

'continue' Statement in C

 The 'continue' statement does not terminate the loop. It just skips the remaining statements in the body of the loop for the current pass and then next pass is started. To use 'continue', you just have to include the keyword'continue' followed by a semicolon.

Example of 'Continue' Statement in C

The below example has an array of integers as input and it iterates over each number checking if each number of negative or positive. If it's positive, the program calculates the square of the number, else it goes to the next number.
  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4. int a[5] = {1, -2, 3, -4, 5};
  5. int i;
  6. for (i = 0; i < 5; i++ ) {
  7. if (a[i] < 0)
  8. continue;
  9. printf("%d * %d = %d\n", a[i], a[i], a[i] * a[i]);
  10. }
  11. return 0;
  12. }
  13.  
  14. Output:
  15. 1 * 1 = 1
  16. 3 * 3 = 9
  17. 5 * 5 = 25
The program iterates over each number and when the number is less than 0, the 'continue'statement is executed and control goes to the next iteration of loop.

'goto' Statement

The 'goto' statement is used to transfer the control of execution of the program to another part of the program where a particular label is defined. The 'goto' statement is used alongside a label and has the general form goto label;
The label is the identifier which defines where the control should go on the execution of 'goto'statement. The target statement block must be labelled like - label: statement /statement block

Example of 'goto' Statement in C

Take look at the following simple program.
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int i;
  5. for(i = 0; i < 10; i++)
  6. {
  7. if(i == 5)
  8. {
  9. goto out;
  10. }
  11. printf("%d\n", i);
  12. }
  13.  
  14. out:
  15. printf("I am tired now\n");
  16. }
This program will print the values 0 to 4 and when value of 'i' reaches 5, execution jumps to the statement with label 'out'. Then it will just print the string "I am tired now" and will exit from the program.
One advantage of 'goto' statement is that unlike 'break''goto' can exit from all nested loops. Also, if you use 'goto' correctly, you can write a block that loops multiple times without using forwhile or do...while loop. Following piece of code is an example of that.
  1. int i = 0;
  2. a:
  3. if(i < 10)
  4. {
  5. printf("%d\n", i);
  6. i++;
  7. goto a;
  8. }

Monday, February 22, 2016

'break' Statement in C

'break' Statement Example in C

Let’s take a look at an example of how to use 'break' statement with 'for'loop.
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int i;
  5. int number;
  6.  
  7. printf("Enter a number:");
  8. scanf("%d", &number);
  9.  
  10. for(i = 2; i < number; i++)
  11. {
  12. if((number % i) == 0)
  13. {
  14. printf("%d is not prime", number);
  15. break;
  16. }
  17. }
  18. }
The above program will check if the input number is a prime or not and if the number is not prime, program will print stating so. The program starts with index variable 'i' initialized with the value 2 (which gets incremented in each cycle of loop) and checks if the input number is divisible by'i'. If it is divisible by any number other than 1 and itself, then it's not a prime and we don't need to try remaining values. So, after 'printf' statement, the 'break' will take the program control out of 'for' loop.
The program given below prints the non-prime numbers between 5 and 20 using a nested loop. The outer loop iterates from 5 to 20 and the inner loop checks if the number is prime or not. If number is not prime, inner loop prints that and the 'break' statement takes the control out of inner loop. That means, control is taken back to the outer loop, which begin to process with the next value for loop variable 'i'
  1. #include<stdio.h>
  2. void main()
  3. {
  4. int i, j;
  5.  
  6. for(i = 5; i <= 20; i++)
  7. {
  8. for(j = 2; j < i; j++)
  9. {
  10. if((i % j) == 0)
  11. {
  12. printf("%d\n", i);
  13. break;
  14. }
  15. }
  16. }
  17. }