C – Header Files

Header Files in C ”; Previous Next The #include preprocessor directive is used to make the definitions of functions, constants and macros etc. from one file, usually called as a header file, available for use in another C code. A header file has “.h” extension from which you can include the forward declarations of one or more predefined functions, constants, macros etc. The provision of header files in C facilitates a modular design of the program. System Header Files The C compiler software is bundled with many pre-compiled header files. These are called system header files. A well-known example is “stdio.h” – a header file included in almost every C program. Each of the system header files contains a number of utility functions. These functions are often called library functions. For example, printf() and scanf() functions, needed for performing IO operations, are the library functions available in the “stdio.h” header file. The preprocessor statements that load one or more header files are always in the beginning of the C code. We start our journey to learn C programming with a basic “Hello World” program that starts with including the “stdio.h” file − #include <stdio.h> int main() { /* my first program in C */ printf(“Hello, World! n”); return 0; } The C preprocessing directive #include basically is a request to the compiler to load the contents of a specific header file, so that they can be used in the program. A usual practice in C or C++ programs is that we keep all the constants, macros, system wide global variables, and function prototypes in the header files and include that header file wherever it is required. Syntax to Include Header Files in C A header file is loaded with the #include directive. Its usage follows either of the following two methods − #include <filename.h> The name of the header file put inside angular brackets if it is available in system/default directory. #include “filename.h” The name of the header file put inside double quotation marks for user defined or non-standard header files available in same directory as source file The #include directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current source file. The output from the preprocessor contains the output already generated, followed by the output resulting from the included file, followed by the output that comes from the text after the #include directive. Standard Header Files in C A typical C compiler is bundled with a number of pre-compiled header files. Each header file contains the set of predefined standard library functions. The “#include” preprocessing directive is used to include the header files with “.h” extension in the program. Here is the table that displays some of the header files in C language − Header Files Description Functions/macros/variables stdio.h Input/Output functions scanf(), printf(), fopen(), FILE stdlib.h General utility functions atoi(), atof(), malloc() math.h Mathematics functions sin(), cos(), pow(), sqrt() string.h String functions strcpy(), strlen(), strcat() ctype.h Character handling functions isalpha(), isupper(), ispunct() time.h Date and time functions asctime(), gmtime(), mktime() float.h Limits of float types FLT_ROUNDS, FLT_RADIX, limits.h Size of basic types CHAR_BIT, CHAR_MIN, CHAR_MAX wctype.h Functions to determine the type contained in wide character data. iswalpha(), iswctype(),iswupper() Example A few of the library functions from some header files are used in the code below − #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main() { char s1[20] = “53875”; char s2[10] = “Hello”; char s3[10] = “World”; int res; res = pow(8, 4); printf(“Using math.h, The value is : %dn”, res); long int a = atol(s1); printf(“Using stdlib.h, the string to long int: %dn”, a); strcpy(s2, s3); printf(“Using string.h, the strings s2 and s3: %st%sn”, s2, s3); return 0; } Output When you run this code, it will produce the following output − Using math.h, The value is: 4096 Using stdlib.h, the string to long int: 53875 Using string.h, the strings s2 and s3: World World User-defined Header Files We can add one or more user-defined functions (apart from the main() function) in the C program. However, if the code consists of a large number of function definitions, putting them in a single source code file with “.c” extension becomes difficult to handle and maintain. Hence, functions/macros/variables of similar nature are clubbed together in header files, and included as we include the standard header files, and call the functions defined in them. The user-defined header files are usually placed in the same directory in which the C source code is present. The procedure to create and use a header file with CodeBlocks IDE has been described below. Start CodeBlocks IDE and create a new Console Application − Choose a suitable name to the project. Add a new empty file in the folder, and save the following code as “myheader.h” − #ifndef MYHEADER_H #define MYHEADER_H void sayHello(); int add(int a, int b); double area(double radius); int length(char *x); #endif If a header file happens to be included twice, the compiler will process its contents twice and it will result in an error. The standard way to prevent this is to enclose the entire real contents of the file in a conditional definition with #ifndef directive, known as a header guard. The header guard checks whether the header file has been defined or not. If it”s not defined,

C – Random Number Generation

Random Number Generation in C ”; Previous Next The stdlib.h library in C includes the rand() function that returns an integer randomly, between “0” and the constant RAND_MAX. The rand() function generates pseudo-random numbers. They are not truly random. The function works on Linear Congruential Generator (LCG) algorithm. int rand(void); Example 1 The following code calls the rand() function thrice, each time it is likely to come with a different integer − #include <stdio.h> #include<stdlib.h> int main() { printf(“%ldn”, rand()); printf(“%ldn”, rand()); printf(“%ldn”, rand()); return 0; } Output Run the code and check its output − 41 18467 6334 The rand() function doesn”t have a built-in mechanism to set the seed. By default, it might use a system specific value (often based on the time the program starts). Note: The srand() function is used to improve the randomness by providing a seed to the rand() function. Example 2 The following program returns a random number between 0 to 100. The random integer returned by the rand() function is used as a numerator and its mod value with 100 is calculated to arrive at a random number that is less than 100. #include <stdio.h> #include<stdlib.h> int main(){ for(int i = 1; i <= 5; i++) { printf(“random number %d: %d n”, i, rand() % 100); } return 0; } Output Run the code and check its output − random number 1: 41 random number 2: 67 random number 3: 34 random number 4: 0 random number 5: 69 Example 3 You can also obtain a random number between a given range. You need to find the mod value of the result of rand() divided by the range span, add the result to the lower value of the range. #include <stdio.h> #include<stdlib.h> int main() { int i, num; int lower=50, upper=100; for (i = 1; i <= 5; i++) { num = (rand() % (upper – lower + 1)) + lower; printf(“random number %d: %d n”, i,num); } return 0; } Output Run the code and check its output − random number 1: 91 random number 2: 55 random number 3: 60 random number 4: 81 random number 5: 94 The srand() Function The stdlib.h library also includes the srand() function that is used to seed the rand() function’s random number generator. You would use the following syntax to use the srand() function − void srand (unsigned seed); OR int srand (unsigned int seed); The seed parameter is an integer value to be used as seed by the pseudo-random number generator algorithm. Note: If srand() is not initialized, then the seed value in rand() function is set as srand(1). Usually, the srand() function is used with the value returned by time(NULL) (which represents the current time since the epoch) as a parameter to improve the randomness of the pseudo-random numbers generated by rand() in C. Since the time value changes all the time, this will have different seed values, leading to more varied random sequences. As a result, if you generate random number multiple times, then it will likely result in different random value every time. Example 1 Take a look at the following example − #include <stdio.h> #include<stdlib.h> #include <time.h> int main() { srand(time(NULL)); printf(“Random number: %d n”, rand()); return 0; } Output Every time a new random integer between 0 to RAND_MAX will be displayed. Random number: 1436786055 Example 2 We can include srand() to generate a random number between a given range. #include <stdio.h> #include<stdlib.h> #include <time.h> int main() { int i, num; time_t t; int lower = 100, upper = 200; srand((unsigned) time(&t)); for (i = 1; i <=5; i++) { num = (rand() % (upper – lower + 1)) + lower; printf(“random number number %d: %d n”, i, num); } return 0; } Output Run the code and check its output − random number number 1: 147 random number number 2: 171 random number number 3: 173 random number number 4: 112 random number number 5: 181 The random number generation offered by rand() function is not truly random. With the same seed, you”ll always get the same sequence. It also has a limited range as it generates random numbers within a specific range (0 to RAND_MAX). To improving the Randomness, you need to use a good seed value with high unpredictability like system time or a high-resolution timer. You can also use third party libraries for wider range random numbers. Print Page Previous Next Advertisements ”;

C – Typedef

Typedef in C ”; Previous Next C typedef The C programming language provides a keyword called typedef to set an alternate name to an existing data type. The typedef keyword in C is very useful in assigning a convenient alias to a built-in data type as well as any derived data type such as a struct, a union or a pointer. Sometimes it becomes clumsy to use a data type with a longer name (such as “struct structname” or “unsigned int“) every time a variable is declared. In such cases, we can assign a handy shortcut to make the code more readable. typedef Syntax In general, the typedef keyword is used as follows − typedef existing_type new_type; typedef Examples In this chapter, let us have a look at some of the use-cases of typedef. Example 1 In C language, the keyword “unsigned” is used to declare unsigned integer variables that can store only non-negative values. C also has a keyword called “short” that declares an integer data type that occupies 2 bytes of memory. If you want to declare a variable that is short and can have only non-negative values, then you can combine both these keywords (unsigned and short): short unsigned int x; If there are going to be many variables to be declared of this type, it will not be very convenient to use these three keywords every time. Instead, you can define an alias or a shortcut with the typedef keyword as follows − typedef short unsigned int USHORT; This tells the compiler that the identifier USHORT corresponds to “short unsigned int” type. Hereafter, you can use USHORT in the variable declaration statement − USHORT x; Example 2 C also has the keyword static to indicate that such a variable is initialized only once. The keyword “long” allocates 8 bytes to store an integer on a 64-bit system. We can declare a variable of this type as follows − static unsigned long x; However, we can’t use the keyword “static” in a “typedef” statement, however we can use typedef to assign a shortcut alias to this type of declaration − typedef signed long SLONG; static SLONG x; Note: As a convention, the alias names are expressed in uppercase, just to differentiate between the built-in type and the aliases used. Example 3 The following example demonstrates how you can use alias names in a C program − #include <stdio.h> int main() { typedef short unsigned int USHORT; typedef signed long int SLONG; static SLONG x = 100; USHORT y = 200; printf(“Size of SLONG: %d nSize of USHORT: %d”, sizeof(SLONG), sizeof(USHORT)); return 0; } Output When you run this code, it will produce the following ouput − Size of SLONG: 8 Size of USHORT: 2 Defining a Structure using Typedef Normally, we need to declare a struct variable by prefixing the name of struct_type in the declaration statement as − struct struct_type var; If writing the type name in this manner feels cumbersome, then you can use typedef to assign an alias − typedef struct struct_type ALIAS; Example In this example, we define a structure type and then use the typedef keyword to set an alias for it − #include <stdio.h> int main() { typedef unsigned long int ULONG; typedef short int SHORT; struct mystruct { ULONG a; SHORT b; }; typedef struct mystruct STR; STR s1 = {10, 20}; printf(“%ld %u”, s1.a, s1.b); return 0; } Output Run the code and check its output − 10 20 There is an alternate approach to use the typedef keyword. We can combine it in the structure definition itself, as given below − typedef struct mystruct { ULONG a; SHORT b; } STR; STR s1 = {10, 20}; Typedef for Struct Pointer The typedef keyword may also be used to assign a new identifier to any pointer type. Normally, we declare a pointer variable as follows − struct mystruct * x; Instead, we can use the typedef keyword as follows − typedef struct mystruct { ULONG a; SHORT b; } STR; typedef STR * strptr; It allows you to declare a pointer of this type in a much more concise way − strptr ptr; We can then assign the address of a corresponding struct variable to the pointer. Example The following example shows how you can use typedef to create a struct prointer − #include <stdio.h> int main() { typedef unsigned long int ULONG; typedef short int SHORT; typedef struct mystruct { ULONG a; SHORT b; } STR; STR s1 = {10, 20}; typedef STR * strptr; strptr ptr = &s1; printf(“%d %d n”, s1.a, s1.b); printf(“%d %d”, ptr->a, ptr->b); return 0; } Output When you run this code, it will produce the following output − 10 20 10 20 Typedef for Union We can use the typedef keyword to assign a shortcut alias to any union type. Example The following example illustrates how you can use typedef in creating unions − #include <stdio.h> int main() { typedef unsigned long int ULONG; typedef short int SHORT; typedef union myunion { char a; int b; double c; } UNTYPE; UNTYPE u1; u1.c = 65.50; typedef UNTYPE * UNPTR; UNPTR ptr = &u1; printf(“a:%c b: %d c: %lf n”, u1.a, u1.b, u1.c); printf(“a:%c b: %d c: %lf n”, ptr->a, ptr->b, ptr->c); return 0; } Output Run the code and

C – Self-Referential Structures

Self-referential Structures in C ”; Previous Next What are Self-referential Structures? A self-referential structure is a struct data type in C, where one or more of its elements are pointer to variables of its own type. Self-referential user-defined types are of immense use in C programming. They are extensively used to build complex and dynamic data structures such as linked lists and trees. In C programming, an array is allocated the required memory at compile-time and the array size cannot be modified during the runtime. Self-referential structures let you emulate the arrays by handling the size dynamically. File management systems in Operating Systems are built upon dynamically constructed tree structures, which are manipulated by self-referential structures. Self-referential structures are also employed in many complex algorithms. Defining a Self-referential Structure A general syntax of defining a self-referential structure is as follows − strut typename{ type var1; type var2; … … struct typename *var3; } Let us understand how a self-referential structure is used, with the help of the following example. We define a struct type called mystruct. It has an integer element “a” and “b” is the pointer to mystruct type itself. We declare three variables of mystruct type − struct mystruct x = {10, NULL}, y = {20, NULL}, z = {30, NULL}; Next, we declare three “mystruct” pointers and assign the references x, y and z to them. struct mystruct * p1, *p2, *p3; p1 = &x; p2 = &y; p3 = &z; The variables “x”, “y” and “z” are unrelated as they will be located at random locations, unlike the array where all its elements are in adjacent locations. Examples of Self-referential Structure Example 1 To explicitly establish a link between the three variable, we can store the address of “y” in “x” and the address of “z” in “y”. Let us implement this in the following program − #include <stdio.h> struct mystruct{ int a; struct mystruct *b; }; int main(){ struct mystruct x = {10, NULL}, y = {20, NULL}, z = {30, NULL}; struct mystruct * p1, *p2, *p3; p1 = &x; p2 = &y; p3 = &z; x.b = p2; y.b = p3; printf(“Address of x: %d a: %d Address of next: %dn”, p1, x.a, x.b); printf(“Address of y: %d a: %d Address of next: %dn”, p2, y.a, y.b); printf(“Address of z: %d a: %d Address of next: %dn”, p3, z.a, z.b); return 0; } Output Run the code and check its output − Address of x: 659042000 a: 10 Address of next: 659042016 Address of y: 659042016 a: 20 Address of next: 659042032 Address of z: 659042032 a: 30 Address of next: 0 Example 2 Let us refine the above program further. Instead of declaring variables and then storing their address in pointers, we shall use the malloc() function to dynamically allocate memory whose address is stored in pointer variables. We then establish links between the three nodes as shown below − #include <stdio.h> #include <stdlib.h> struct mystruct{ int a; struct mystruct *b; }; int main(){ struct mystruct *p1, *p2, *p3; p1 = (struct mystruct *)malloc(sizeof(struct mystruct)); p2 = (struct mystruct *)malloc(sizeof(struct mystruct)); p3 = (struct mystruct *)malloc(sizeof(struct mystruct)); p1 -> a = 10; p1->b=NULL; p2 -> a = 20; p2->b=NULL; p3 -> a =30; p3->b=NULL; p1 -> b = p2; p2 -> b = p3; printf(“Add of x: %d a: %d add of next: %dn”, p1, p1->a, p1->b); printf(“add of y: %d a: %d add of next: %dn”, p2, p2->a, p2->b); printf(“add of z: %d a: %d add of next: %dn”, p3, p3->a, p3->b); return 0; } Output Run the code and check its output − Add of x: 10032160 a: 10 add of next: 10032192 add of y: 10032192 a: 20 add of next: 10032224 add of z: 10032224 a: 30 add of next: 0 Example 3 We can reach the next element in the link from its address stored in the earlier element, as “p1 → b” points to the address of “p2”. We can use a while loop to display the linked list, as shown in this example − #include <stdio.h> #include <stdlib.h> struct mystruct{ int a; struct mystruct *b; }; int main(){ struct mystruct *p1, *p2, *p3; p1=(struct mystruct *)malloc(sizeof(struct mystruct)); p2=(struct mystruct *)malloc(sizeof(struct mystruct)); p3=(struct mystruct *)malloc(sizeof(struct mystruct)); p1 -> a = 10; p1 -> b = NULL; p2 -> a = 20; p2 -> b = NULL; p3 -> a = 30; p3 -> b = NULL; p1 -> b = p2; p2 -> b = p3; while (p1 != NULL){ printf(“Add of current: %d a: %d add of next: %dn”, p1, p1->a, p1->b); p1 = p1 -> b; } return 0; } Output Run the code and check its output − Add of current: 10032160 a: 10 add of next: 10032192 Add of current: 10032192 a: 20 add of next: 10032224 Add of current: 10032224 a: 30 add of next: 0 Creating a Linked List with Self-referential Structure In the above examples, the dynamically constructed list has three discrete elements linked with pointers. We can use a for loop to set up required number of elements by allocating memory dynamically, and store the address of next element in the previous node. Example The following example shows how you can create a linked list using a self-referential structure − #include <stdio.h> #include <stdlib.h> struct mystruct{ int a; struct mystruct *b; }; int main(){ struct mystruct *p1, *p2, *start; int i; p1 = (struct mystruct *)malloc(sizeof(struct mystruct)); p1 -> a = 10;

C – Memory Management

Memory Management in C ”; Previous Next One of the important characteristics of C is that the compiler manages how the memory is allocated to the variables declared in the code. Once the compiler allocates the required bytes of memory, it cannot be changed during the runtime. The compiler employs static memory allocation approach. However, there are times where you may need to allocate the memory on demand, during the runtime. Read this chapter to understand how dynamic memory management works in C. Functions for Dynamic Memory Management in C The C programming language provides several functions for dynamic memory allocation and management. These functions can be found in the <stdlib.h> header file. Function Description void *calloc(int num, int size); This function allocates an array of num elements each of which size in bytes will be size. void free(void *address); This function releases a block of memory block specified by address. void *malloc(size_t size); This function allocates an array of num bytes and leave them uninitialized. void *realloc(void *address, int newsize); This function re-allocates memory extending it up to newsize. Allocating Memory Dynamically If you are aware of the size of an array, then it is easy and you can define it as an array. For example, if you need to store the name of a person, then you can safely define an array to hold a maximum of 100 characters (assuming that a name wouldn”t contain more than 100 characters). So, you can define an array as follows − char name[100]; This is an example of static memory allocation. Now let us consider a situation where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. In such a case, if the content is less than the allocated size, the allocated memory is wasted during the program’s execution. On the other hand, if the size required is more than the allocated memory size, it may lead to unpredictable behaviour, including causing the data to be corrupted, as the size of the array cannot be dynamically altered. It is in these kind of situations you need to use the dynamic memory allocation methods as described in this chapter. The malloc() Function This function is defined in the stdlib.h header file. It allocates a block memory of the required size and returns a void pointer. void *malloc (size) The size parameter refers to the block of memory in bytes. To allocate a memory required for a specified data type, you need to use the typecasting operator. For example, the following snippet allocates the memory required to store an int type − int *ptr; ptr = (int *) malloc (sizeof (int)); Here we need to define a pointer to character without defining how much memory is required and later, based on requirement, we can allocate memory. Example The following example uses the malloc() function to allocate the required memory to store a string (instead of declaring a char array of a fixed size) − #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *name; name = (char *) malloc(strlen(“TutorialsPoint”)); strcpy(name, “TutorialsPoint”); if(name == NULL) { fprintf(stderr, “Error – unable to allocate required memoryn”); } else { printf(“Name = %sn”, name); } } Output When the above code is compiled and executed, it produces the following output − Name = TutorialsPoint The calloc() Function The calloc() function (stands for contiguous allocation) allocates the requested memory and returns a pointer to it. void *calloc(n, size); Here, “n” is the number of elements to be allocated and “size” is the byte-size of each element. The following snippet allocates the memory required to store 10 int types − int *ptr; ptr = (int *) calloc(25, sizeof(int)); Example Let”s rewrite the above program using the calloc() function. All that you need to do is replace malloc with calloc − #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *name; name = (char *) calloc(strlen(“TutorialsPoint”), sizeof(char)); strcpy(name, “TutorialsPoint”); if(name == NULL) { fprintf(stderr, “Error – unable to allocate required memoryn”); } else { printf(“Name = %sn”, name); } } So you have complete control and you can pass any size value while allocating memory, unlike arrays where once the size is defined, you cannot change it. Resizing and Releasing the Memory When your program comes out, the operating system automatically releases all the memory allocated by your program. However, it is a good practice to release the allocated memory explicitly by calling the free() function, when you are not in need of using the allocated memory anymore. In this section, we will highlight the use of two functions, realloc() and free(), that you can use to resize and release the allocated memory. The realloc() Function The realloc() (re-allocation) function in C is used to dynamically change the memory allocation of a previously allocated memory. You can increase or decrease the size of an allocated memory block by calling the realloc() function. The prototype of using the realloc() function is like this − void *realloc(*ptr, size); Here, the first parameter “ptr” is the pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the function. The second parameter “size” is the new size for the memory block, in bytes. If it is “0” and ptr points to an existing block of memory, the memory

C – Command Execution

Command Execution in C ”; Previous Next Command Execution in C Command execution in C is used to execute the system command using the C program. The system commands are executed by using the system() function which is a library function of stdlib.h header file. By using the system() function, you can execute the Windows/Linux terminal commands inside a C program. Syntax The following is the syntax to execute system commands − system(char *command); Example of Command Execution The following code shows the execution of ls command using system() function in C language. #include <stdio.h> #include<stdlib.h> #include<string.h> int main() { char cmd[10]; strcpy(cmd,”dir C:\users\user\*.c”); system(cmd); return 0; } Output Run the code and check its output − C:Usersuser>dir *.c Volume in drive C has no label. Volume Serial Number is 7EE4-E492 Directory of C:Usersuser 04/01/2024 01:30 PM 104 add.c 04/02/2024 01:37 PM 159 add1.c 04/02/2024 01:37 PM 259 array.c 04/02/2024 01:37 PM 149 main.c 04/02/2024 01:37 PM 180 recursion.c 04/02/2024 01:37 PM 241 struct.c 04/02/2024 01:37 PM 172 voidptr.c 7 File(s) 1,264 bytes 0 Dir(s) 139,073,761,280 bytes exec Family of Functions in C The exec family of functions have been introduced in the “unistd.h” header file. These functions are used to execute a file, and they replace the current process image with a new process image once they are called. The following are the functions of exec family in C − execl() Function execlp() Function execle() Function execv() Function execvp() Function execve() Function 1. execl() Function The execl() function”s first argument is the executable file as its first argument. The next arguments will be available to the file when it”s executed. The last argument has to be NULL. int execl(const char *pathname, const char *arg, …, NULL) Example Take a look at the following example − #include <unistd.h> int main(void) { char *file = “/usr/bin/echo”; char *arg1 = “Hello world!”; execl(file, file, arg1, NULL); return 0; } The echo command in Linux is being invoked through the C code. Output Save, compile, and execute the above program − $ gcc hello.c -o hello $ ./hello Hello world! 2. execlp() Function The execlp() function is similar to the execl() function. It uses the PATH environment variable to locate the file. Hence, the path to the executable file needn”t be given. int execlp(const char *file, const char *arg, …, NULL) Example Take a look at the following example − #include <unistd.h> int main(void) { char *file = “echo”; char *arg1 = “Hello world!”; execlp(file, file, arg1, NULL); return 0; } Output Here, echo is already located in the PATH environment variable. Save, compile and run from the terminal. $ gcc hello.c -o hello $ ./hello Hello world! 3. execle() Function In the execle() function, we can pass environment variables to the function, and it”ll use them. Its prototype is like this − int execle(const char *pathname, const char *arg, …, NULL, char *const envp[]) Example Take a look at the following example − #include <unistd.h> int main(void) { char *file = “/usr/bin/bash”; char *arg1 = “-c”; char *arg2 = “echo $ENV1 $ENV2!”; char *const env[] = {“ENV1 = Hello”, “ENV2 = World”, NULL}; execle(file, file, arg1, arg2, NULL, env); return 0; } Output Save, compile, and run from the terminal − $ gcc hello.c -o hello $ ./hello Hello world! 4. execv() Function The execv() function receives a vector of arguments that will be available to the executable file. In addition, the last element of the vector has to be NULL: int execv(const char *pathname, char *const argv[]) Example Take a look at the following example − #include <unistd.h> int main(void) { char *file = “/usr/bin/echo”; char *const args[] = {“/usr/bin/echo”, “Hello world!”, NULL}; execv(file, args); return 0; } Output Save, compile, and execute the above program − $ gcc hello.c -o hello $ ./hello Hello world! 5. execvp() Function The execvp() has the following syntax − int execvp(const char *file, char *const argv[]) Example Take a look at the following example − #include <unistd.h> int main(void) { char *file = “echo”; char *const args[] = {“/usr/bin/echo”, “Hello world!”, NULL}; execvp(file, args); return 0; } Output Save, compile, and execute the above program − $ gcc hello.c -o hello $ ./hello Hello world! 6. execve() Function In addition to environment variables, we can pass other arguments to execve() function as a NULL-terminated vector − int execve(const char *pathname, char *const argv[], char *const envp[]) Example Take a look at the following example − #include <unistd.h> int main(void) { char *file = “/usr/bin/bash”; char *const args[] = {“/usr/bin/bash”, “-c”, “echo Hello $ENV!”, NULL}; char *const env[] = {“ENV=World”, NULL}; execve(file, args, env); return 0; } Output Save, compile, and execute the above program − $ gcc hello.c -o hello $ ./hello Hello world! Print Page Previous Next Advertisements ”;

C – Quick Guide

C – Quick Guide ”; Previous Next C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been written in C. C has now become a widely used professional language for various reasons − Easy to learn Structured language It produces efficient programs It can handle low-level activities It can be compiled on a variety of computer platforms Facts about C C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around the early 1970s. The language was formalized in 1988 by the American National Standard Institute (ANSI). The UNIX OS was totally written in C. Today C is the most widely used and popular System Programming Language. Most of the state-of-the-art software have been implemented using C. Today”s most popular Linux OS and RDBMS MySQL have been written in C. Why use C? C was initially used for system development work, particularly the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as the code written in assembly language. Some examples of the use of C might be − Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Databases Language Interpreters Utilities C Programs A C program can vary from 3 lines to millions of lines and it should be written into one or more text files with extension “.c”; for example, hello.c. You can use “vi”, “vim” or any other text editor to write your C program into a file. This tutorial assumes that you know how to edit a text file and how to write source code inside a program file. C – Environment Setup Local Environment Setup If you want to set up your environment for C programming language, you need the following two software tools available on your computer, (a) Text Editor and (b) The C Compiler. Text Editor This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi. The name and version of text editors can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX. The files you create with your editor are called the source files and they contain the program source codes. The source files for C programs are typically named with the extension “.c“. Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it. The C Compiler The source code written in source file is the human readable source for your program. It needs to be “compiled”, into machine language so that your CPU can actually execute the program as per the instructions given. The compiler compiles the source codes into final executable programs. The most frequently used and free available compiler is the GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective operating systems. The following section explains how to install GNU C/C++ compiler on various OS. We keep mentioning C/C++ together because GNU gcc compiler works for both C and C++ programming languages. Installation on UNIX/Linux If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line − $ gcc -v If you have GNU compiler installed on your machine, then it should print a message as follows − Using built-in specs. Target: i386-redhat-linux Configured with: ../configure –prefix=/usr ……. Thread model: posix gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/ This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS flavor of the Linux system. Installation on Mac OS If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple”s web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++. Xcode is currently available at developer.apple.com/technologies/tools/. Installation on Windows To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage, www.mingw.org, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe. While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more. Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names. After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line. C – Program Structure Before we study the basic building blocks of the C programming language, let us look at a bare minimum C program structure so that we can take it as a reference in the upcoming chapters. Hello World Example A C program basically consists of the following parts − Preprocessor Commands Functions Variables Statements & Expressions Comments Let us look at a simple code that would print the words “Hello World” − Live Demo #include <stdio.h> int main() { /*

C – Anonymous Structure and Union

Anonymous Structures and Unions in C ”; Previous Next Anonymous Structures and Unions in C The feature of anonymous structures and unions was introduced in C11 standard. The aim was to enhance the flexibility of C and also to discard the need of superfluous naming in certain cases. The feature of defining struct and union anonymously has been found to be extremely useful, especially in applications involving the creation of complex data structures, hardware register mappings, etc. This allows for more straightforward and readable code. Anonymous Structure An anonymous structure is a structure definition without a tag or a typedef. It is usually nested within another struct. Syntax for Anonymous Struct Here is the syntax of defining an anonymous structure − struct type { elem1; elem2; struct { elem3; elem4; }; }; Access Members of Anonymous Structure Members of an anonymous struct/union can access the parent struct directly, simplifying the notation. Example 1 In the code below, we have defined a structure with the name as employee. Inside it, an anonymous struct is intended to hold date, month and year of birth of the employee. In the example on nested structure, we had an internal dob structure. Now we’ll use anonymous struct. #include <stdio.h> struct employee { char name[10]; float salary; struct { int d, m, y; }; }; int main(){ struct employee e1; strcpy (e1.name, “Kiran”); e1.salary=25000; e1.d = 12; e1.m = 5; e1.y = 1990; printf(“Name: %sn”, e1.name); printf(“Salary: %fn”, e1.salary); printf(“Date of Birth: %d-%d-%dn”, e1.d, e1.m, e1.y); return 0; } Output When you run this code, it will produce the following output − Name: Kiran Salary: 25000.000000 Date of Birth: 12-5-1990 Note that the “d”, “m” and “y” elements of inner anonymous struct are accessed directly. Example 2 The outer struct type in the following example is student, which has a nested anonymous struct to store the title and ID of the course. #include <stdio.h> struct student { char name[10]; int age; struct { char coursettl[20]; int courseid; }; }; int main(){ struct student s1; strcpy (s1.name, “Kiran”); s1.age = 27; strcpy(s1.coursettl, “C Programming”); s1.courseid=1; printf(“Name: %sn”, s1.name); printf(“age: %dn”, s1.age); printf(“Course Title: %s Course ID: %dn”, s1.coursettl, s1.courseid); return 0; } Output When you run this code, it will produce the following output − Name: Kiran age: 27 Course Title: C Programming Course ID: 1 Anonymous Union An anonymous union is a special type of union that doesn”t have a name. Unlike regular unions, anonymous unions are primarily used to create unnamed members that can be accessed directly without qualifying them with a union name. Syntax for Anonymous Union Here is the syntax of defining an anonymous union − struct type { elem1; elem2; union { elem3; elem4; }; }; Access Members of Anonymous Union The members of the anonymous union can be accessed directly without using a union name. Example Anonymous unions do not have a name. The elements share the same memory location. Take a look at the following example − #include <stdio.h> struct mystruct { int var; union { int var1; float var2; char var3; }; }; int main(){ struct mystruct data; data.var = 10; data.var2 = 5.55; printf(“mystruct.var: %dn”, data.var); printf(“anonymous union elements: %d %f %c”, data.var1, data.var2, data.var3); return 0; } Output Run the code and check its output − mystruct.var: 10 anonymous union elements: 1085381018 5.550000 � Note: Like a regular union, the uninitialized members of an anonymous union variable also show garbage value. Advantages of Anonymous Struct and Union One of the main advantages is the ability to access the members directly without any inner struct or union name. This can make the code more readable. Here is a list of some other advantages of using anonymous structures and unions − Memory Efficiency − Like regular unions, anonymous unions allow different data types to share the same memory space, leading to more memory-efficient code, especially useful in low-memory environments. Flexibility − Anonymous structures provide flexibility in how data is represented and accessed, allowing for more dynamic and versatile data structures. Convenience − This feature allows for a compact representation of a variable that can hold different data types. Ease of Initialization − They can be easier to initialize and use, as they do not require the declaration of a union variable. Note that anonymous struct or union types were not part of the C standard before C11. Hence, their use in the code may lead to compatibility problems, if the target system uses a compiler compliant with earlier standards. Print Page Previous Next Advertisements ”;

C – Math Functions

Math Functions in C ”; Previous Next C Math Functions C language provides various functions to perform mathematical operations on numbers such as finding trigonometric ratios, calculating log and exponentials, rounding the numbers, etc.. To use these math functions in a C program, you need to include math.h header file. We have categorized math functions into the following categories − Trigonometric Functions Inverse Trigonometric Functions Hyperbolic Functions Exponentiation and Logarithmic Functions Floating-Point Functions Power and Square Root Functions Rounding Functions Modulus Functions Trigonometric Functions The math.h library defines the function sin(), cos(), and tan() – that return the respective trigonometric ratios, sine, cosine and tangent of an angle. These functions return the respective ratio for a given double type representing the angle expressed in radians. All the functions return a double value. double sin(double x) double cos(double x) double tan(double x) For all the above functions, the argument “x” is the angle in radians. Example The following example shows how you can use trigonometric functions in C − #include <stdio.h> #include <math.h> #define PI 3.14159265 int main() { double x, sn, cs, tn, val; x = 45.0; val = PI / 180; sn = sin(x*val); cs = cos(x*val); tn = tan(x*val); printf(“sin(%f) : %fn”, x, sn); printf(“cos(%f) : %fn”, x, cs); printf(“tan(%f) : %fn”, x, tn); return(0); } Output When you run this code, it will produce the following output − sin(45.000000) : 0.707107 cos(45.000000) : 0.707107 tan(45.000000) : 1.000000 Inverse Trigonometric Functions The math.h library also includes inverse trigonometric functions, also known as arcus functions or anti-trigonometric functions. They are the inverse functions of basic trigonometric functions. For example, asin(x) is equivalent to $&bsol;mathrm{sin^{-1}(x)}$. The other inverse functions are acos(), atan() and atan2(). The following asin() function returns the arc sine of “x” in the interval [-pi/2, +pi/2] radians − double asin(double x) The following acos() function returns principal arc cosine of “x” in the interval [0, pi] radians − double acos(double x) The following atan() function returns the principal arc tangent of “x” in the interval [-pi/2, +pi/2] radians. double atan(double x) Example 1 The following example demonstrates how you can use inverse trigonometric functions in a C program − #include <stdio.h> #include <math.h> #define PI 3.14159265 int main() { double x, asn, acs, atn, val; x = 0.9; val = 180/PI; asn = asin(x); acs = acos(x); atn = atan(x); printf(“asin(%f) : %f in radiansn”, x, asn); printf(“acos(%f) : %f in radiansn”, x, acs); printf(“atan(%f) : %f in radiansn”, x, atn); asn = (asn * 180) / PI; acs = (acs * 180) / PI; atn = (atn * 180) / PI; printf(“asin(%f) : %f in degreesn”, x, asn); printf(“acos(%f) : %f in degreesn”, x, acs); printf(“atan(%f) : %f in degreesn”, x, atn); return(0); } Output When you run this code, it will produce the following output − asin(0.900000) : 1.119770 in radians acos(0.900000) : 0.451027 in radians atan(0.900000) : 0.732815 in radians asin(0.900000) : 64.158067 in degrees acos(0.900000) : 25.841933 in degrees atan(0.900000) : 41.987213 in degrees The atan2() function returns the arc tangent in radians of “y/x” based on the signs of both values to determine the correct quadrant. double atan2(double y, double x) This function returns the principal arc tangent of “y / x” in the interval [-pi, +pi] radians. Example 2 Take a look at the following example − #include <stdio.h> #include <math.h> #define PI 3.14159265 int main() { double x, y, ret, val; x = -7.0; y = 7.0; val = 180.0 / PI; ret = atan2 (y,x) * val; printf(“The arc tangent of x = %lf, y = %lf “, x, y); printf(“is %lf degreesn”, ret); return(0); } Output Run the code and check its output − The arc tangent of x = -7.000000, y = 7.000000 is 135.000000 degrees Hyperbolic Functions In Mathematics, hyperbolic functions are similar to trigonometric functions but are defined using the hyperbola rather than the circle. The math.h header file provides sinh(), cosh(), and tanh() functions. double sinh(double x) This function returns hyperbolic sine of x. double cosh(double x) This function returns hyperbolic cosine of x. double tanh(double x) This function returns hyperbolic tangent of x. Example The following example shows how you can use hyperbolic functions in a C program − #include <stdio.h> #include <math.h> #define PI 3.14159265 int main() { double x,val, sh, ch, th; x = 45; val = PI/180.0 ; sh = sinh(x*val); ch = cosh(x*val); th = tanh(x*val); printf(“The sinh(%f) = %lfn”, x, sh); printf(“The cosh(%f) = %lfn”, x, ch); printf(“The tanh(%f) = %lfn”, x, th); return(0); } Output Run the code and check its output − The sinh(45.000000) = 0.868671 The cosh(45.000000) = 1.324609 The tanh(45.000000) = 0.655794 Exponentiation and Logarithmic Functions The “math.h” library includes the following functions related to exponentiation and logarithms − exp() Function: It returns the value of e raised to the xth power. (Value of e – Euler’s number – is 2.718 approx) double exp(double x) log() Function: It returns the natural logarithm (base-e logarithm) of “x”. double log(double x) Note that Logarithmic functions are equivalent to the exponential function’s inverse. log10() Function: It returns the common logarithm (base-10 logarithm) of “x”. double log10(double x) Example The following example shows how you can use exponentiation and logarithmic

C – Identifiers

C – Identifiers ”; Previous Next Identifier in C helps in identifying variables, constants, functions etc., in a C code. C, being a high-level computer language, allows you to refer to a memory location with a name instead of using its address in binary or hexadecimal form. C Identifiers Identifiers are the user-defined names given to make it easy to refer to the memory. It is also used to define various elements in the program, such as the function, user-defined type, labels, etc. Identifiers are thus the names that help the programmer to use programming elements more conveniently. When a variable or a function is defined with an identifier, the C compiler allocates it the memory and associates the memory location to the identifier. As a result, whenever the identifier is used in the instruction, C compiler can access its associated memory location. For example, when we declare a variable age and assign it a value as shown in the following figure, the compiler assigns a memory location to it. Even if the programmer can use an identifier of his choice to name a variable or a function etc., there are certain rules to be followed to form a valid identifier. Naming Rules of C Identifiers Given below are the rules using which an identifier is formed − Keywords can”t be used as identifiers as they are predefined. Out of the character set that C uses, only the alphabets (upper and lowercase) and the underscore symbol (_) are allowed in the identifier. It implies that you can”t use characters like the punctuation symbols etc. as a part of the identifier. The identifier must start either with an alphabet (upper or lowercase) or an underscore. It means, a digit cannot be the first character of the identifier. The subsequent characters may be alphabets or digits or an underscore. Same identifier can”t be used as a name of two entities. An identifier can be used only once in the current scope. As per the above rules, some examples of the valid and invalid identifiers are as follows − Valid C Identifiers age, Age, AGE, average_age, __temp, address1, phone_no_personal, _my_name Invalid C Identifiers Average-age, my name, $age, #phone, 1mg, phy+maths Examples of C Identifiers The following program shows an error − #include <stdio.h> int main () { /* variable definition: */ int marks = 50; float marks = 65.50; printf(“%d %f”, marks, marks); return 0; } Error main.c: In function ”main”: main.c:7:10: error: conflicting types for ”marks”; have ”float” 7 | float marks = 65.50; | ^~~~~ main.c:6:8: note: previous definition of ”marks” with type ”int” 6 | int marks = 50; | ^~~~~ main.c:8:13: warning: format ”%d” expects argument of type ”int”, but argument 2 has type ”double” [-Wformat=] 8 | printf(“%d %f”, marks, marks); | ~^ ~~~~~ | | | | int double | %f Identifiers are case-sensitive, as a result age is not the same as AGE. ANSI standard recognizes a length of 31 characters for an identifier. Although you can choose a name with more characters, only the first 31 will be recognized. Thus you can form a meaningful and descriptive identifier. Scope of C Identifiers In C language, the scope of identifiers refers to the place where an identifier is declared and can be used/accessed. There are two scopes of an identifier: Global Identifiers If an identifier has been declared outside before the declaration of any function, it is called as an global (external) identifier. Example #include <stdio.h> int marks= 100; // external identifier int main() { printf(“The value of marks is %dn”, marks); } Output The value of marks is 100 This is because marks is defined outside of any blocks, so it is an external identifier. Local Identifiers On the other hand, an identifier inside any function is an local (internal) identifier. Example #include <stdio.h> int main() { int marks= 100; // internal identifier printf(“The value of marks is %dn”, marks); } Output The value of marks is 100 This is because marks is defined inside main function, so it is an internal identifier. Examples of Different Types of C Identifiers Identifiers can also appear in a forward declaration of a function. However, the declaration signature of a function should match with the definition. Example of Variable Identifier int marks1 = 50, marks2 = 60; float avg = (float) (marks1+marks2)/2; Example of Function Identifier int average(int marks1, int marks2) { return (float) (marks1+marks2)/2; } Example of User-defined Type Identifier struct student { int rollno; char *name; int m1,m2,m3; float percent }; struct student s1 = {1, “Raju”, 50, 60, 70, 60.00}; Example of Typedef Identifier struct student { int rollno; char *name; int m1,m2,m3; float percent }; typedef struct student STUDENT; STUDENT s1 = {1, “Raju”, 50, 60, 70, 60.00}; Example of Label Identifier #include <stdio.h> int main() { int x=0; begin: x++; if (x>=10) goto end; printf(“%dn”, x); goto begin; end: return 0; } Output 1 2 3 4 5 6 7 8 9 Example of Enum Identifier #include <stdio.h> enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun}; int main() { printf(“The value of enum week: %dn”,Mon); return 0; } Output The value of enum week: 10 Thus, the identifiers are found everywhere in the C program. Choosing right identifier for the coding element such as the variable or a function is important for enhancing the readability and debugging and documentation of the program.