C – Pointers

Pointers in C ”; Previous Next What is a Pointer in C? C pointer is the derived data type that is used to store the address of another variable and can also be used to access and manipulate the variable”s data stored at that location. The pointers are considered as derived data types. With pointers, you can access and modify the data located in the memory, pass the data efficiently between the functions, and create dynamic data structures like linked lists, trees, and graphs. Pointer Declaration To declare a pointer, use the dereferencing operator (*) followed by the data type. Syntax The general form of a pointer variable declaration is − type *var-name; Here, type is the pointer”s base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Example of Valid Pointer Variable Declarations Take a look at some of the valid pointer declarations − int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */ The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. Pointer Initialization After declaring a pointer variable, you need to initialize it with the address of another variable using the address of (&) operator. This process is known as referencing a pointer. Syntax The following is the syntax to initialize a pointer variable – pointer_variable = &variable; Example Here is an example of pointer initialization – int x = 10; int *ptr = &x; Here, x is an integer variable, ptr is an integer pointer. The pointer ptr is being initialized with x. Referencing and Dereferencing Pointers A pointer references a location in memory. Obtaining the value stored at that location is known as dereferencing the pointer. In C, it is important to understand the purpose of the following two operators in the context of pointer mechanism − The & Operator − It is also known as the “Address-of operator”. It is used for Referencing which means taking the address of an existing variable (using &) to set a pointer variable. The * Operator − It is also known as the “dereference operator”. Dereferencing a pointer is carried out using the * operator to get the value from the memory address that is pointed by the pointer. Pointers are used to pass parameters by reference. This is useful if a programmer wants a function”s modifications to a parameter to be visible to the function”s caller. This is also useful for returning multiple values from a function. Access and Manipulate Values using Pointer The value of the variable which is pointed by a pointer can be accessed and manipulated by using the pointer variable. You need to use the asterisk (*) sign with the pointer variable to access and manipulate the variable”s value. Example In the below example, we are taking an integer variable with its initial value and changing it with the new value. #include <stdio.h> int main() { int x = 10; // Pointer declaration and initialization int * ptr = & x; // Printing the current value printf(“Value of x = %dn”, * ptr); // Changing the value * ptr = 20; // Printing the updated value printf(“Value of x = %dn”, * ptr); return 0; } Output Value of x = 10 Value of x = 20 How to Use Pointers? To use the pointers in C language, you need to declare a pointer variable, then initialize it with the address of another variable, and then you can use it by dereferencing to get and change the value of the variables pointed by the pointer. You can use pointers with any type of variable such as integer, float, string, etc. You can also use pointers with derived data types such as array, structure, union, etc. Example In the below example, we are using pointers for getting values of different types of variables. #include <stdio.h> int main() { int x = 10; float y = 1.3f; char z = ”p”; // Pointer declaration and initialization int * ptr_x = & x; float * ptr_y = & y; char * ptr_z = & z; // Printing the values printf(“Value of x = %dn”, * ptr_x); printf(“Value of y = %fn”, * ptr_y); printf(“Value of z = %cn”, * ptr_z); return 0; } Output Value of x = 10 Value of y = 1.300000 Value of z = p Size of a Pointer Variable The memory (or, size) occupied by a pointer variable does not depend on the type of the variable it is pointing to. The size of a pointer depends on the system architecture. Example In the below example, we are printing the size of different types of pointers: #include <stdio.h> int main() { int x = 10; float y = 1.3f; char z = ”p”; // Pointer declaration and initialization int * ptr_x = & x; float * ptr_y = & y; char * ptr_z = & z; // Printing the size of pointer variables printf(“Size of integer pointer

C – Array of Pointers

Array of Pointers in C ”; Previous Next What is an Array of Pointers? Just like an integer array holds a collection of integer variables, an array of pointers would hold variables of pointer type. It means each variable in an array of pointers is a pointer that points to another address. The name of an array can be used as a pointer because it holds the address to the first element of the array. If we store the address of an array in another pointer, then it is possible to manipulate the array using pointer arithmetic. Create an Array of Pointers To create an array of pointers in C language, you need to declare an array of pointers in the same way as a pointer declaration. Use the data type then an asterisk sign followed by an identifier (array of pointers variable name) with a subscript ([]) containing the size of the array. In an array of pointers, each element contains the pointer to a specific type. Example of Creating an Array of Pointers The following example demonstrates how you can create and use an array of pointers. Here, we are declaring three integer variables and to access and use them, we are creating an array of pointers. With the help of an array of pointers, we are printing the values of the variables. #include <stdio.h> int main() { // Declaring integers int var1 = 1; int var2 = 2; int var3 = 3; // Declaring an array of pointers to integers int *ptr[3]; // Initializing each element of // array of pointers with the addresses of // integer variables ptr[0] = &var1; ptr[1] = &var2; ptr[2] = &var3; // Accessing values for (int i = 0; i < 3; i++) { printf(“Value at ptr[%d] = %dn”, i, *ptr[i]); } return 0; } Output When the above code is compiled and executed, it produces the following result − Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200 There may be a situation when we want to maintain an array that can store pointers to an “int” or “char” or any other data type available. An Array of Pointers to Integers Here is the declaration of an array of pointers to an integer − int *ptr[MAX]; It declares ptr as an array of MAX integer pointers. Thus, each element in ptr holds a pointer to an int value. Example The following example uses three integers, which are stored in an array of pointers, as follows − #include <stdio.h> const int MAX = 3; int main(){ int var[] = {10, 100, 200}; int i, *ptr[MAX]; for(i = 0; i < MAX; i++){ ptr[i] = &var[i]; /* assign the address of integer. */ } for (i = 0; i < MAX; i++){ printf(“Value of var[%d] = %dn”, i, *ptr[i]); } return 0; } Output When the above code is compiled and executed, it produces the following result − Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200 An Array of Pointers to Characters You can also use an array of pointers to character to store a list of strings as follows − #include <stdio.h> const int MAX = 4; int main(){ char *names[] = { “Zara Ali”, “Hina Ali”, “Nuha Ali”, “Sara Ali” }; int i = 0; for(i = 0; i < MAX; i++){ printf(“Value of names[%d] = %sn”, i, names[i]); } return 0; } Output When the above code is compiled and executed, it produces the following result − Value of names[0] = Zara Ali Value of names[1] = Hina Ali Value of names[2] = Nuha Ali Value of names[3] = Sara Ali An Array of Pointers to Structures When you have a list of structures and want to manage it using a pointer. You can declare an array of structures to access and manipulate the list of structures. Example The below example demonstrates the use of an array of pointers to structures. #include <stdio.h> #include <stdlib.h> #include <string.h> // Declaring a structure typedef struct { char title[50]; float price; } Book; const int MAX = 3; int main() { Book *book[MAX]; // Initialize each book (pointer) for (int i = 0; i < MAX; i++) { book[i] = malloc(sizeof(Book)); snprintf(book[i]->title, 50, “Book %d”, i + 1); book[i]->price = 100 + i; } // Print details of each book for (int i = 0; i < MAX; i++) { printf(“Title: %s, Price: %.2fn”, book[i]->title, book[i]->price); } // Free allocated memory for (int i = 0; i < MAX; i++) { free(book[i]); } return 0; } Output When the above code is compiled and executed, it produces the following result − Title: Book 1, Price: 100.00 Title: Book 2, Price: 101.00 Title: Book 3, Price: 102.00 Print Page Previous Next Advertisements ”;

C – Callback Function

Callback Function in C ”; Previous Next Callback functions are extremely versatile, particularly in event-driven programming. When a specific event is triggered, a callback function mapped to it is executed in response to these events. This is typically used in GUI applications, an action like a button click can initiate a series of predefined actions. Callback Function The callback function is basically any executable code that is passed as an argument to other code, that is expected to call back or execute the argument at a given time. We can define it in other words like this: If the reference of a function is passed to another function argument for calling, then it is called a callback function. The mechanism of callbacks depends on function pointers. A function pointer is a variable that stores the memory address of a function. Here is a simple hello() function in C − void hello(){ printf(“Hello World.”); } We declare a pointer to this function as follows − void (*ptr)() = &hello; We can now call the function with the help of this function pointer, (*ptr)(); Example of Callback Function in C In this example, the hello() function is defined as an argument to myfunction(). #include <stdio.h> void hello(){ printf(“Hello Worldn”); } void callback(void (*ptr)()){ printf(“Calling a function with its pointern”); (*ptr)(); // calling the callback function } main(){ void (*ptr)() = hello; callback(ptr); } Output Calling a function with its pointer Hello World Callback Function With Arguments In the example given below, we have also declared two functions with identical prototypes − square() and root(). int square(int val){ return val*val; } int root(int val){ return pow(val, 0.5); } The callback function is defined to receive an argument as well as a function pointer with an integer argument that matches with the above functions. int callback(int a, int (*ptr)(int)){ int ret = (*ptr)(a); return ret; } In the main() function, we place a call to the callback by passing an integer and the name of the function (square / root) which becomes the function pointer in callback’s definition. Example of Callback Function With Arguments The complete code is as follows − #include <stdio.h> #include <math.h> int callback(int a, int (*print_callback)(int)); int square(int value); int root (int value); int main(){ int x = 4; printf(“Square of x: %d is %dn”, x, callback(x, square)); printf(“Square root of x: %d is %dn”, x, callback(x, root)); return 0; } int callback(int a, int (*ptr)(int)){ int ret = (*ptr)(a); return ret; } int square(int val){ return val*val; } int root(int val){ return pow(val, 0.5); } Output Square of x: 4 is 16 Square root of x: 4 is 2 Types of Callbacks in C There are two types of callbacks − Synchronous Callback A callback is synchronous when it is given to another function, which executes it as part of its process. The calling function waits for the callback to complete before proceeding. This is useful when you need immediate results or want to ensure a task is finished before moving on. Asynchronous Callback In this case, the calling function triggers the callback but doesn’t wait for it to finish. Instead, it continues its execution. It results in non-blocking operations. It’s commonly used in event-driven programming. Generic callback functions help developers write C programs that are versatile and better adaptable. In this chapter, we explained how you can use function pointers so that we can enhance the flexibility of our C programs. Additionally, we showed how you can create generic callback functions that are not limited to a specific function pointer type. Print Page Previous Next Advertisements ”;

C – Structures and Functions

Structures and Functions in C ”; Previous Next In C programming, struct is a derived data type. Just as we can pass arguments of primary data types, a variable of struct data type can also be passed to a function. You can also pass structures using call by value and call by reference methods. A function in C may also return a struct data type. Read this chapter to understand the following concepts − How to pass elements of struct type How to pass a struct variable How to return struct from a function How to return a struct pointer Let”s start with the first one and learn how to pass elements of struct type. How to Pass Struct Elements A derived type is a combination of one or more elements of any of the primary types as well as another derived type. It is possible to pass elements to a function, either by value or by reference. Example In the following example, we have a derived type called “rectangle” with two elements. We have a struct variable “r” with the elements “r.len” and “l.brd” and they are passed to a function. The area() function then computes the area of the rectangle. #include <stdio.h> struct rectangle{ float len, brd; }; int area(float, float); int main(){ struct rectangle r; r.len = 10.50; r.brd = 20.5; area(r.len, r.brd); return 0; } int area(float a, float b){ double area = (double)(a*b); printf(“Length: %f nBreadth: %f nArea: %lfn”, a, b, area); return 0; } Output When you run this code, it will produce the following output − Length: 10.500000 Breadth: 20.500000 Area: 215.250000 How to Pass a Struct Variable Let us modify the above example to pass the struct variable itself (instead of its elements) to the area() function. The rectangle struct type also has an additional element called “area”. Example Inside the function, the elements of the struct variable are accessed though the dot operator (.) and the area is calculated. #include <stdio.h> struct rectangle{ float len, brd; double area; }; int area(struct rectangle); int main(){ struct rectangle r; r.len = 10.50; r.brd = 20.5; area(r); return 0; } int area(struct rectangle r){ r.area = (double)(r.len*r.brd); printf(“Length: %f nBreadth: %f nArea: %lfn”, r.len, r.brd, r.area); return 0; } Output Run the code and check its output − Length: 10.500000 Breadth: 20.500000 Area: 215.250000 How to Return Struct from a Function We know that a function in C can return a value of any type. In this example, the area() function is defined to return a struct variable. Example Inside the main() fuction, the inputs for the length and the breadth are passed to the area() function. Inside the area() function, the area is computed and a struct variable is populated and returned to the main() function, where its elements are displayed. #include <stdio.h> struct rectangle { float len, brd; double area; }; struct rectangle area(float x, float y); int main(){ struct rectangle r; float x, y; x = 10.5; y = 20.5; r = area(x, y); printf(“Length: %f n Breadth: %f n Area: %lfn”, r.len, r.brd, r.area); return 0; } struct rectangle area(float x, float y){ double area = (double)(x*y); struct rectangle r = {x, y, area}; return r; } Output When you run this code, it will produce the following output − Length: 10.500000 Breadth: 20.500000 Area: 215.250000 How to Pass a Struct by Reference In C language, a function may be defined to have its arguments passed by value or reference. A reference is the pointer to an existing variable. Example In this example, a struct variable of “rectangle” type is declared in main() and its address is passed to a user-defined function called area(). When the area() function is called, it can use the elements of the variable with the indirection operator (→). It computes the result and assigns it to the area element “r → area”. #include <stdio.h> struct rectangle{ float len, brd; double area; }; int area(struct rectangle *); int main(){ struct rectangle r; r.len = 10.50; r.brd = 20.5; area(&r); return 0; } int area(struct rectangle *r){ r -> area = (double)(r -> len * r -> brd); printf(“Length: %f nBreadth: %f nArea: %lfn”, r -> len, r -> brd, r -> area); return 0; } Output Run the code and check its output − Length: 10.500000 Breadth: 20.500000 Area: 215.250000 How to Return a Struct Pointer Let us rewrite the above code to define the area() function and return a pointer to a struct of rectangle data type. Example The area() function has two call-by-value arguments. The main() function reads the length and breadth from the user and passes them to the area() function, which populates a struct variable and passes its reference back to the main() function. #include <stdio.h> struct rectangle { float len, brd; double area; }; struct rectangle * area(float x, float y); int main (){ struct rectangle *r; float x, y; x = 10.5; y = 20.5; r = area(x, y); printf(“Length: %f n Breadth: %f n Area: %lfn”, r->len, r->brd, r->area); return 0; } struct rectangle * area(float x, float y){ double area = (double)(x*y); static struct rectangle r; r.len = x; r.brd = y; r.area = area; return &r; } Output When you run this code, it will produce the following output −

C – Lookup Tables

Lookup Tables in C ”; Previous Next Lookup tables (popularly known by the abbreviation LUT) in C are arrays populated with certain pre-computed values. Lookup tables help avoid performing a lot of calculations in a program. Instead of lengthy nested if-else statements or switch statements, one can use Lookup tables to enhance the efficiency of a C program. Example 1 Let us have a look at a simple application of a lookup table. In the following code, we compute the square of a given integer. #include <stdio.h> int square(int x){ return x*x; } int main(){ int num[5] = {1, 2, 3, 4, 5}; for (int i = 0; i <= 4; i++){ printf(“No: %d tSquare(%d): %dn”, i+1, i+1, square(i+1)); } return 0; } Output When you run this code, it will produce the following output − No: 1 Square(1): 1 No: 2 Square(2): 4 No: 3 Square(3): 9 No: 4 Square(4): 16 No: 5 Square(5): 25 Example 2 While the above program works satisfactorily, it involves frequent calls to the square() function, for each value of the array index. Instead, we can declare an array to store the squares of numbers and access the computed square directly from the index. #include <stdio.h> int main(){ int squares[5] = {1, 4, 9, 16, 25}; for (int i = 0; i <= 4; i++){ printf(“No: %d tSquare(%d): %dn”, i+1, i+1, squares[i]); } return 0; } Output Run the code and check its output − No: 1 Square(1): 1 No: 2 Square(2): 4 No: 3 Square(3): 9 No: 4 Square(4): 16 No: 5 Square(5): 25 Example 3 In the example below, we fetch the name of the element corresponding to its atomic number. # include <stdio.h> int main(){ int num = 3; switch (num){ case 1: puts(“Hydrogen”); break; case 2: puts(“Helium”); break; case 3: puts(“Lithium”); break; case 4: puts(“Beryllium”); break; case 5: puts(“Boron”); break; default: puts(“error: unknown element!”); } return 0; } Output It will produce the following output − Lithium Example 4 Instead of a lengthy switch statements with a case for each element, we use a lookup table (an array populated with the names of all the elements) to simplify the program − #include <stdio.h> static const char *table[] = { “Hydrogen”, “Helium”, “Lithium”, “Beryllium”, “Boron” }; int main(){ int num = 3; if (num >= 1 && num <= 5){ printf(“Name of the element with atomic number %d is %s”, num, table[num-1]); } else { puts(“error: Atomic number not in the lookup table!”); } return 0; } Output Run the code and check its output − Name of the element with atomic number 3 is Lithium Lookup Tables in 7-Segment LED Display Lookup tables are extensively used in the design of embedded systems, as they enhance the performance of the application. In many devices, the seven-segment LED display is used to show visual output. Eight segments of the unit are illuminated based on a sequence of binary digits. We use a lookup table to convert numbers ranging from 0 to 9 to seven-segment signals to drive a display. Example The 7-segment binary code for the number is stored as an array element. The hexadecimal code is then converted to binary code that will drive the 7-segment display. #include <stdio.h> int main(){ // Array to represent numbers 0-9 in 7-segment display binary encoding int const nums[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f}; static int bin[8]; int i = 0, num = 7, rem; printf(“The binary equivalent of 7 is: “); for (i = 7; i >= 0; i–){ rem = num % 2; bin[i] = rem; num /= 2; } for (i = 0; i <= 7; i++){ printf(“%d”, bin[i]); if (i == 3) printf(” “); } return 0; } Output Run the code and check its output − The binary equivalent of 7 is: 0000 0111 The least significant bits represent segments “a”, “b”, “c” and “d”. The most significant bits are “e”, “f”, “g” and “h”. The segments “a”, “b” and “c” illuminate to display 7, leaving the other segments off. Print Page Previous Next Advertisements ”;

C – User-Defined Functions

User-defined Functions in C ”; Previous Next A function in C is a block of organized, reusable code that is used to perform a single related action. In any C program, there are one or more functions − classified as library functions and user-defined functions. There are two types of functions in C − Library functions User-defined functions Any C compiler (e.g. GCC compiler, Clang, MSVC compiler, etc.) is distributed with a number precompiled header files (stdio.h, math.h, etc.), each consisting of one or more predefined library functions such as printf(), scanf(), pow(), sqrt(), etc. To be able to use the library function, the corresponding header file must be made available with the #include directive. However, if you don’t find a suitable library function to serve your purpose, then you can define a customized function for the program. Normally, we find a C program with a main() function. Obviously, the main() function is a user-defined function, as it contains the instructions provided by the user. It can of course call the other library or user-defined functions. What is User-Defined Function in C? User-defined function is defined by the user to perform specific task to achieve the code reusability and modularity. To create and use the user-defined function, you do not need use any built-in library. These functions can be created either in the same program or in user-defined header file. Creating a User-defined Function For creating a user-defined function, first you need to understand the purpose of the function, that is, what do you want the function to do? To create a user-defined function, you need to know about the following three parts of a function: Function declaration Function definition Function calling Declaration of User-defined Function In C language, it is necessary to provide the declaration of the prototype of any function. The prototype of a library function is present in the corresponding header file. For a user-defined function, its prototype is present in the current program. The definition of a function and its prototype declaration should match. Syntax If you wish to define a function called add() that performs the addition of two integer arguments and returns the value as an integer, then the function declaration would be as follows − int add(int, int); Definition of User-defined Function The definition of a function and its prototype declaration should match. The definition consists of a function header that matches the declaration and a function body. Syntax return_type function_name(arg1, arg2, …){ // Function body; return val; } Example Using this template, you can write the user-defined function add() as follows − int add(int a, int b){ int c; c = a + b; return c; } Note that the order of definition of user-defined functions is not important in a C program. However, its prototype must be declared before calling the function. In a program, the main() function is always the entry point, irrespective of whether it is the first function or not. We needn”t provide the prototype declaration of the main() function. Calling a User-defined Function To call a function, you should use a statement that complies with the declaration of the function prototype. If the function is defined to receive a certain number of arguments, then the same number and type of arguments must be passed to call that function. Example The following statement calls the add() function that we defined above − int result = add(10, 20); Example of User-Defined Function In this example, we are create two user-defined functions add() and sub() to find the addition and subtraction of the given numbers. // C program to demonstrate an example of // user-defined function #include <stdio.h> // Function declarations int add(int, int); int sub(int, int); // Function definitions int add(int a, int b) { return (a + b); } int sub(int a, int b) { return (a – b); } int main() { // Declaring two integer variables to // store the numbers // and resultant variables to store the result int num1 = 36, num2 = 24; int res_add, res_sub; // Calling the functions res_add = add(num1, num2); res_sub = sub(num1, num2); // Printing the results printf(“Addition is : %dn”, res_add); printf(“Subtraction is : %dn”, res_sub); return 0; } Addition is : 60 Subtraction is : 12 Formal and Actual Arguments in User-Defined Function When a function is defined with arguments, the arguments in the parenthesis in front of the function name are called formal arguments. In the above example, the function is defined with “int a” and “int b” arguments; they are formal arguments. When the function is called, the arguments passed to it are called the actual arguments. In the example below, the variables “x” and “y” are the actual arguments. int x = 10, y = 20; int result = add(x, y); A user-defined function may be defined to have any type of variables as formal arguments. It includes primary types (int, float, char), array, pointer, or struct/union type variables. A function should return a value to the calling environment. By default, the return type of a function is int type. However, it can return any data type − primary type, array, pointer, or a struct as well as a pointer. You can even define a function that returns a void type. Example If either the number or the type of actual and formal arguments or the return type as in the forward declaration of a function and its definition don’t match, then the compiler reports an error. Look at the example below − #include <stdio.h>

C – Nested Functions

Nested Functions in C ”; Previous Next The term nesting, in programming context refers to enclosing a particular programming element inside another similar element. Just like nested loops, nested structures, etc., a nested function is a term used to describe the use of one or more functions inside another function. What is Lexical Scoping? In C language, defining a function inside another one is not possible. In short, nested functions are not supported in C. A function may only be declared (not defined) within another function. When a function is declared inside another function, it is called lexical scoping. Lexical scoping is not valid in C because the compiler cannot reach the correct memory location of inner function. Nested Functions Have Limited Use Nested function definitions cannot access local variables of surrounding blocks. They can access only global variables. In C, there are two nested scopes: local and global. So, nested functions have limited use. Example: Nested Function If you want to create a nested function like the one shown below, then it will generate an error − #include <stdio.h> int main(void){ printf(“Main Function”); int my_fun(){ printf(“my_fun function”); // Nested Function int nested(){ printf(“This is a nested function.”); } } nested(); } Output On running this code, you will get an error − main.c:(.text+0x3d): undefined reference to `nested” collect2: error: ld returned 1 exit status Trampolines for Nested Functions Nested functions are supported as an extension in “GNU C”. GCC implements taking the address of a nested function using a technique called trampolines. A trampoline is a piece of code created at runtime when the address of a nested function is taken. It requires the function to be prefixed with the keyword auto in the declaration. Example 1 Take a look at the following example − #include <stdio.h> int main(){ auto int nested(); nested(); printf(“In Main Function nown”); int nested(){ printf(“In the nested function nown”); } printf(“End of the program”); } Output When you run this code, it will produce the following output − In the nested function now In Main Function now End of the program Example 2 In thi program, a function square() is nested inside another function myfunction(). The nested function is declared with the auto keyword. #include <stdio.h> #include <math.h> double myfunction (double a, double b); int main(){ double x = 4, y = 5; printf(“Addition of squares of %f and %f = %f”, x, y, myfunction(x, y)); return 0; } double myfunction (double a, double b){ auto double square (double c) { return pow(c,2); } return square (a) + square (b); } Output Run the code and check its output − Addition of squares of 4.000000 and 5.000000 = 41.000000 Nested Functions: Points to Note One needs to be aware of the following points while using nested functions − A nested function can access all the identifiers of the containing function that precede its definition. A nested function must not be called before the containing function exits. A nested function cannot use a goto statement to jump to a label in the containing function. Nested function definitions are permitted within functions in any block, mixed with the other declarations and statements in the block. If you try to call a nested function through its address after the containing function exits, it throws an error. A nested function always has no linkage. Declaring one with “extern” or “static” always produces errors. Print Page Previous Next Advertisements ”;

C – Scope Rules

C – Scope Rules ”; Previous Next A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language − Inside a function or a block which is called local variables. Outside of all functions which is called global variables. In the definition of function parameters which are called formal parameters. Let us understand what are local and global variables, and formal parameters. Local Variables Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Example The following example shows how local variables are used. Here all the variables a, b, and c are local to main() function. #include <stdio.h> int main () { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf (“value of a = %d, b = %d and c = %dn”, a, b, c); return 0; } Global Variables Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Example The following program show how global variables are used in a program. #include <stdio.h> /* global variable declaration */ int g; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf (“value of a = %d, b = %d and g = %dn”, a, b, g); return 0; } A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an example − Example #include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf (“value of g = %dn”, g); return 0; } When the above code is compiled and executed, it produces the following result − value of g = 10 Formal Parameters Formal parameters, are treated as local variables with-in a function and they take precedence over global variables. Following is an example − Example #include <stdio.h> /* global variable declaration */ int a = 20; int main () { /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0; printf (“value of a in main() = %dn”, a); c = sum( a, b); printf (“value of c in main() = %dn”, c); return 0; } /* function to add two integers */ int sum(int a, int b) { printf (“value of a in sum() = %dn”, a); printf (“value of b in sum() = %dn”, b); return a + b; } When the above code is compiled and executed, it produces the following result − value of a in main() = 10 value of a in sum() = 10 value of b in sum() = 20 value of c in main() = 30 Initializing Local and Global Variables When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows − Data Type Initial Default Value int 0 char ”” float 0 double 0 pointer NULL It is a good programming practice to initialize variables properly, otherwise your program may produce unexpected results, because uninitialized variables will take some garbage value already available at their memory location. Print Page Previous Next Advertisements ”;

C – Return Statement

Return Statement in C ”; Previous Next The return statement terminates the execution of a function and returns control to the calling function. Every function should have a return statement as its last statement. While using the returns statement, the return type and returned value (expression) must be the same. Syntax of return Statement Here is the syntax of the return statement: return value_or_expression; The following main() function shows return as its last statement − int main(){ // function body; return 0; } The main() function returning 0 indicates the successful completion of the function. To indicate failure of the function, a non−zero expression is returned. The void return statement A function”s return type can be void. In such a case, return statement is optional. It may be omitted, or return without any expression is used. Example #include <stdio.h> /* function declaration */ void test(){ return; } int main() { test(); printf(“end”); return 0; } Return type mismatch in return statement Each function in the program must have a forward declaration of its prototype. By default, each function returns an integer. However, function of other return types without prototype is not accepted. Example int main(){ test(5); printf(“end”); return 0; } float test(int a) { return 1.1 ; } Output Error: C:Usersmlathtest.c|12|error: conflicting types for ”test” This is because, function without prototype is assumed as of int type, which conflicts with the definition. The same error occurs if the return type of a function in the prototype doesn”t match with the type of return expression, an error is reported as below − float test(int); int main(){ test(5); printf(“end”); return 0; } float test(float a){ return 1.1 ; } Multiple return values with return statement A function can be defined with more than one arguments, but can return only one value. You can however use multiple conditional return statements as shown below − Example int test(int); int main() { test(5); printf(“end”); return 0; } int test(int a){ if (a<3) return 1; else return 0; } Function returning an array It is not possible to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array”s name without an index. Example The following program shows how to pass an array to a function that returns an array after performing a certain process. #include <stdio.h> int* test(int *); int main(){ int a[] = {1,2,3,4}; int i; int *b = test(a); for (i=0; i<4; i++){ printf(“%dn”, b[i]); } return 0; } int * test(int*a){ int i; for (i=0; i<4; i++){ a[i] = 2*a[i]; } return a; } Output 2 4 6 8 function can only return a single value using return statement. To return multiple values, we use pointers or structures exit() instead of return statement Unlike the return statement, the exit() function is also used to terminate the execution of the program without transferring the control back to the calling function. It is used inside a function when the program has finished its execution or when an unrecoverable error occurs. It is a standard way of handling exception errors in C. When exit() is called, the program control does not return to the point where exit() was invoked. Instead, the control is handed back to the operating system. The exit() function is library function defined in stdlib.h header file. Syntax void exit(int status); exit() is typically called from the main() function or any other function to terminate the entire program. It is included in the <stdlib.h> header file. Since it results in termination of the program, exit() does not return a value directly to the caller function. Instead, it terminates the program and returns a status code. It is an integer that represents the exit status of the program, indicating success or failure. Print Page Previous Next Advertisements ”;

C – Character Pointers and Functions

Character Pointers and Functions in C ”; Previous Next What is a Character Pointer in C? A character pointer stores the address of a character type or address of the first character of a character array (string). Character pointers are very useful when you are working to manipulate the strings. There is no string data type in C. An array of “char” type is considered as a string. Hence, a pointer of a char type array represents a string. This char pointer can then be passed as an argument to a function for processing the string. Declaring a Character Pointer A character pointer points to a character or a character array. Thus, to declare a character pointer, use the following syntax: char *pointer_name; Initializing a Character Pointer After declaring a character pointer, you need to initialize it with the address of a character variable. If there is a character array, you can simply initialize the character pointer by providing the name of the character array or the address of the first elements of it. Character Pointer of Character The following is the syntax to initialize a character pointer of a character type: char *pointer_name = &char_variable; Character Pointer of Character Array The following is the syntax to initialize a character pointer of a character array (string): char *pointer_name = char_array; /*or*/ char *pointer_name = &char_array[0]; Character Pointer Example In the following example, we have two variables character and character array. We are taking two pointer variables to store the addresses of the character and character array, and then printing the values of the variables using the character pointers. #include <stdio.h> int main() { // Declare two variables char x = ”P”; char arr[] = “TutorialsPoint”; // Declaring character pointers char *ptr_x = &x; char *ptr_arr = arr; // Printing values printf(“Value of x : %cn”, *ptr_x); printf(“Value of arr: %sn”, ptr_arr); return 0; } Output Run the code and check its output − Value of x : P Value of arr: TutorialsPoint Understanding Character Pointer A string is declared as an array as follows − char arr[] = “Hello”; The string is a NULL terminated array of characters. The last element in the above array is a NULL character (). Declare a pointer of char type and assign it the address of the character at the 0th position − char *ptr = &arr[0]; Remember that the name of the array itself is the address of 0th element. char *ptr = arr; A string may be declared using a pointer instead of an array variable (no square brackets). char *ptr = “Hello”; This causes the string to be stored in the memory, and its address stored in ptr. We can traverse the string by incrementing the ptr. while(*ptr != ””){ printf(“%c”, *ptr); ptr++; } Accessing Character Array If you print a character array using the %s format specifier, you can do it by using the name of the character pointer. But if you want to access each character of the character array, you have to use an asterisk (*) before the character pointer name and then increment it. Example Here is the full program code − #include <stdio.h> int main(){ char arr[] = “Character Pointers and Functions in C”; char *ptr = arr; while(*ptr != ””){ printf(“%c”, *ptr); ptr++; } } Output Run the code and check its output − Character Pointers and Functions in C Example Alternatively, pass ptr to printf() with %s format to print the string. #include <stdio.h> int main(){ char arr[] = “Character Pointers and Functions in C”; char *ptr = arr; printf(“%s”, ptr); } Output On running this code, you will get the same output − Character Pointers and Functions in C Character Pointer Functions The “string.h” header files defines a number of library functions that perform string processing such as finding the length of a string, copying a string and comparing two strings. These functions use char pointer arguments. The strlen() Function The strlen() function returns the length, i.e. the number of characters in a string. The prototype of strlen() function is as follows − int strlen(char *) Example 1 The following code shows how you can print the length of a string − #include <stdio.h> #include <string.h> int main(){ char *ptr = “Hello”; printf(“Given string: %s n”, ptr); printf(“Length of the string: %d”, strlen(ptr)); return 0; } When you run this code, it will produce the following output − Given string: Hello Length of the string: 5 Example 2 Effectively, the strlen() function computes the string length as per the user-defined function str_len() as shown below − #include <stdio.h> #include <string.h> int str_len(char *); int main(){ char *ptr = “Welcome to Tutorialspoint”; int length = str_len(ptr); printf(“Given string: %s n”, ptr); printf(“Length of the string: %d”, length); return 0; } int str_len(char *ptr){ int i = 0; while(*ptr != ””){ i++; ptr++; } return i; } When you run this code, it will produce the following output − Given string: Welcome to Tutorialspoint Length of the string: 25 The strcpy() Function The assignment operator ( = ) is not used to assign a string value to a string variable, i.e., a char pointer. Instead, we need to use the strcpy() function with the following prototype − char * strcpy(char * dest, char * source); Example 1 The following example shows