Skip to main content

Posts

Showing posts from December, 2013

Nested function in C

What is nested function? If a function is defined inside another function, then it is called as nested function.  Nested function example in C: Consider the following example, int add(int a, int b) {        void print(int res) {          printf("Result is %d, res);       }       print(a+b);       return 0; } Here, print() is a nested function.  Because, it is defined inside another function named add() . Example C program using nested functions: #include <stdio.h> void add(int a, int b) { void print(int res) { // nested function printf("Result is %d\n", res); return; } print(a + b); // passing sum of a and b as parameter return; } int main() { add(10, 20); return 0; }   Output:   jp@jp-VirtualBox:~/$ ./a.out   Result is 30 Previous Next

Static function in c

What is static function in C? Static function is nothing but a function that is callable only by other functions in the same file where the static function is defined. Static function example : Consider the following example, // static.c is the file name static int add(int a, int b) { return (a + b); } Here, we have defined a static function named add() in static.c.  Below is main.c file which has main function calling another function named add(). // main.c #include <stdio.h> int main() { int res; res = add(10, 20); // main function makes call to static function printf("Result: %d\n", res); return 0; } Let us try to compile both together to get a single executable.   Output:   jp@jp-VirtualBox:~/$ gcc static.c main.c    /tmp/ccSWRV5a.o: In function `main':   ex45.c:(.text+0x19): undefined reference to `add'   collect2: ld returned 1 exit status From main function, we are calling a static f...

main function in C

main() function is mandatory for any C program.  Because, the program execution starts from main() .  Default return type for main function is an integer.  Return value from main function could help us to find the exit status of a C program. Consider the following example, #include <stdio.h> int main() { int val; printf("Enter an integer: "); scanf("%d", &val); if (val < 0) { printf("%d is negative\n", val); return (-1); } else { printf("%d is positive\n", val); return (val); } }   Output:   jp@jp-VirtualBox:~/$ ./a.out   Enter an integer: -1   -1 is negative   jp@jp-VirtualBox:~/$ echo $?   255  // exit status of the program   jp@jp-VirtualBox:~/$ ./a.out   Enter an integer: 50   50 is positive   jp@jp-VirtualBox:~/$ echo $?   50  // exit status of the program How to get exit ...

How to call functions using function pointers?

What is function pointer? Every function has an address.  We can assign the address of functions to pointers.  Then those pointers are called pointers to functions.  Pointers to function is also called as function pointers Let us see how to call functions using function pointer.  Below is an example function pointer int (*func)(int, int); Here, func is a pointer to a function that takes two integer arguments and returns an integer Consider the following example, int add(int a, int b) {          return (a + b); } int main() {           int (*func) (int, int);           func = add;  //assigning address of function add()           (*func)(10, 20);  // calls the add function           return 0; } Here, "func = add" is equivalent to "func = &add" (& is optional) "(*func)(10, 20)"  is equivalent to "func(10, 20)" (* is option...

Variable arguments in C

In C language, its possible to write functions with variable arguments.  A function that takes variable number of arguments is also called as variadic function.  Below is an example prototype for a variadic function. int func_name(int num, ...); func_name     - name of the function num               - number of arguments in argument list ...(ellipsis)     - used to denote variable arguments Below are the list of macros availabe in 'stdarg.h' used to retrieve variable arguments. void va_start (va_list arg, last_arg) It initializes argument pointer arg to point to first optional argument and last_arg is the last named argument to a function. type va_arg (va list arg, type)   Returns subsequent optional argument and type is data type of the actual argument void va_end (va list arg) Ends the use of variable arguments. Example C program on variable length argument list #include <stdio.h> #include <stdarg.h...

Call by value vs call by reference

Difference between call by value and call by reference There are two types of parameter passing schemes.      1. Call by value      2. Call by reference Call by Value:      A copy of actual arguments are passed to the formal arguments.  So, any modification to formal arguments won't affect the original value of actual arguments. Example C program to illustrate call by value: #include <stdio.h> /* swaps given two number */ void swap(int a, int b) { int tmp; tmp = a; a = b; b = tmp; printf("Inside swap() -> a = %d\tb = %d\n", a, b); return; } int main() { int a, b; printf("Enter two integers: "); scanf("%d%d", &a, &b); swap(a, b); // pass by value printf("Inside main() -> a = %d\tb = %d\n", a, b); return 0; }   Output:   jp@jp-VirtualBox:~/$ ./a.out   Enter two integers: 10 20   Inside swap() ...

Comma operator in C

Basically, comma operator is used to separate expressions.  Consider the following, i++, j++, k++, val = val + 10; Here, there are four expression and they are separated by comma operator.  The above statement is equivalent to the following. i++; j++; k++; val = val + 10; Comma operator is most often used in for statement and function arguments.  Below are few examples on comma operator usage. Example 1: (comma operator in for loop) for (i = 0, j = 0, k = 0; i < 10; i++, j++, k++) {       : : } Example 2: (comma operator in function argument) int add(int a, int b) {  // comma operator       return (a + b); } main() {        add(10, 20);  // comma operator in function argument } Example C program using comma operator #include <stdio.h> void add(int a, int b) { printf("Sum of %d and %d is %d\n", a, b, a + b); } int main() { int i, j, k, val = 0; // variable declaration /*...

sizeof operator in C

It is used to find the size(in bytes) of data type or variable.  Consider the following examples, Example 1: int arr[100]; sizeof(int)            - 4 bytes  // size of an integer sizeof(arr)            - 400 bytes // size of 100 elements in an integer array Example 2: Structure is a user defined compound data type which can have elements of different data types grouped under a common name.  We will see more about structures in forth coming tutorials. struct student {      char name[100];      int age, rollno; }; struct student obj, *ptr sizeof(struct student) - 108 bytes   // size of structure student sizeof(obj)                - 108 bytes  // size of structure variable of type student sizeof(ptr)                 - 4 bytes    // size of pointer to structure of type student The total si...

Pointer operators in C

There are two types of pointer operators.  They are 1. Address operator(&) 2. Indirection operator(*) Address Operator: It is used to get the address of the given  variable.  Consider the following, Example: int a = 10, *ptr; ptr = &a; Here, &a gives us the address of the variable a  and the same is address to pointer variable ptr .  Address operator is also known as reference operator. Indirection operator: It is used to get the value stored in an address.  Consider the following, Example: int a = 10, b, *ptr; ptr = &a;  // referencing(&a) b = *ptr;  // dereferencing(*ptr) Here, ptr has the address of the variable a .  On dereferencing the pointer ptr , we will get the value stored at the address of a . Example C program on pointer operators #include <stdio.h> int main() { int a = 10, b, *ptr; ptr = &a; // referencing (&a) b = *ptr; // dereferencing (*ptr) printf("Valu...

Bitwise shift operators with example

There are two types of shift operators.  They are 1. Left shift operator (<<) 2. Right shift operator(>>) Left shift operator: It is used to shift the bits of the first operand to left by the number of bit places the second operand specifies. Example: 2 << 4 Binary value of 2 is 00000010 00000010 << 4 is 00100000 Decimal value of 00100000 is 32 Right shift operator: It is used to shift the bits of the first operand to right by the number of bit places the second operand specifies. Example: 32 >> 4 Binary value of 32 is 00100000 00100000 >> 4 is 00000010 Decimal value of 00000010 is 2 Example C program on bitwise shift operators #include <stdio.h> int main() { int x = 2, y = 4, res; res = x << y; // left shift x by y printf("%d << %d is %d\n", x, y, res); x = res; res = x >> y; // right shift x by y printf("%d >> %d is %d\n", x, y, res); ...

Null statement

If a statement has only semicolon, then it is called as null statement. Syntax:   ; What is the purpose of null statement? do nothing Example 1: for (i = 0; i < 5; i++) ;   // null statement Here, the body of the for loop is null statement. Example 2: goto label; ........ label: ; Program needs at least one statement below label.  If we have no valid statement to place below label, then we can put null statement below label as shown above. Example c program using null statement #include <stdio.h> main() { int i; for (i = 0; i < 5; printf("Hello world\n"), i++) ; // null statement if (i == 5) goto err; printf("You can't execute me!!"); printf(" Yahoooooooooo!!!\n"); err: ; // null statement behind label }   Output:   jp@jp-VirtualBox:~/$ ./a.out   Hello world   Hello world   Hello world   Hello world   Hello world Previous N...

Compound statement

Compound statement is a set of statements or no statements enclosed within set braces. It is also called as blocks.  Compounds statements are usually used in control flow statements(if, if-else, nested if, for, while, do-while etc). Example 1:   if (a < b) { printf("a is less than b"); printf("I am inside compound statement\n"); } There are two statements inside the if block which are compound statements. Example 2:   for (i = 0; i < 5; i++) { } There is no statement present inside the for loop.  It is also called as compound statement. Example 3:  for (i = 0; i < 5; i++) {       int j = 10;  // variable declaration } Variable declaration is allowed inside blocks.  But, the scope(lifetime) of the variable is only inside the block where it is declared. Example c program using compound statements #include <stdio.h> int main() { int i = 20; /* two statements inside if block */ if (i > 10) { ...

Expression statement

It is possible to convert expressions into statements.  All we need to do is add a semicolon at the end of expressions.  Consider the following, 1 + 1; 2 * 2; 3 / 3; 10 <= 9; All of the above are valid expression statements.  But, they are useless since we are not storing the result of the expression in any variable.  We won't get any compilation error when we include the above statements in our code.  Expression statements are useful when we store the result of the expression in some variable as shown below. x = 1 + 1; y = 2 * 2; res = (10 <= 9); #include <stdio.h> int main() { int x, y, res; 2 + 3; 4 * 9; 10 < 2; x = 2 + 3; y = 4 * 9; res = (10 < 2); printf("Value of x is %d\n", x); printf("Value of y is %d\n", y); printf("Value of res is %d\n", res); return 0; }   Output:   jp@jp-VirtualBox:~/$ ./a.out   Value of x is 5   Value ...

for, while, do-while difference

Now, we are going to see the following in detail. difference between while and do while difference between for and do while difference between for and while Difference between while and do-while loop while loop do-while loop Expression is evaluated at the beginning in while loop. Example:      while (expression) {             statement;      } Expression is evaluated at the end in do-while loop Example:      do {             statement;       } while (expression); while loop executes the statement inside the loop only if the truth value of the expression is not 0. do-while loop executes the statement inside the loop at least once, regardless of whether the expression is true or not. Variable used in expression needs to be initialized at the beginning of the loop or before the loop Example 1:       // initialization - outside loop   ...

Control flow overview

Control flow tell us the order in which instructions need to be executed.  Basically, control statements are of three types. 1. Conditional control statements 2. Loop control structure 3. Direct control flow. Conditional control statements: Below are various conditional control statments availabe in c language. 1. if statement 2. if-else statment 3. else-if statement 4. nested if statments 5. switch statment Loop control structure: Below are various loop control structures available in c language. 1. for 2. while 3. do-while Direct control flow: Below are various direct control flow statements available in c language 1. break 2. continue 3. goto 4. return 5. null statement We will see more about the above topics in detail in the forthcoming tutorials. Previous Next

scanf() and printf() functions

Scanf() function: It is used to read input from the keyboard. int scanf(const char *format, ...); For better understanding, lets rewrite the above as follows. scanf("format specifiers", &v1, &v2, &v3); v1, v2 and v3 are the input variables whose value needs to read from the keyboard.  We need to pass address of the variable as argument to store the input values from keyboard. Here, ampersand(&) represents address. &v1 - address of variable v1 Input value for v1 will be stored at address of variable v1 Format specifier can be any of the following %u  - unsigned int %d  - int %x  - hexadecimal %o  - octal %f  - float %lf - double %c  - char %s  - string scanf("%d", &v1); - inputs integer value scanf("%x", &v2); - inputs hexadecimal value scanf("%f", &v3); - inputs float value printf() function: It prints the given data on the output screen. printf("format specifiers", v1, v2,..vn); Here, format specifier ...