C – void Pointer

void Pointer in C ”; Previous Next void Pointer in C A void pointer in C is a type of pointer that is not associated with any data type. A void pointer can hold an address of any type and can be typecasted to any type. They are also called general-purpose or generic pointers. In C programming, the function malloc() and calloc() return “void *” or generic pointers. Declaring void Pointer This is the syntax you would use to declare a void pointer − void *ptr; Example of void Pointer The following example shows how you can use a void pointer in a C program − #include <stdio.h> int main(){ int a = 10; char b = ”x”; // void pointer holds address of int a void *ptr = &a; printf(“Address of ”a”: %d”, &a); printf(“nVoid pointer points to: %d”, ptr); // it now points to char b ptr = &b; printf(“nAddress of ”b”: %d”, &b); printf(“nVoid pointer points to: %d”, ptr); } Output Run the code and check its output − Address of ”a”: 853377452 Void pointer points to: 853377452 Address of ”b”: 853377451 Void pointer points to: 853377451 An Array of void Pointers We can declare an array of void pointers and store pointers to different data types. A void pointer is a pointer that can hold the memory address of any data type in C. Hence, an array of void pointers is an array that can store memory addresses, but these addresses can point to variables of different data types. You can also store pointers to any user-defined data types such as arrays and structures in a void pointer. Example In this example program, we have declared an array of void pointers and stored in it the pointers to variables of different types (int, float, and char *) in each of its subscripts. #include <stdio.h> int main(){ void *arr[3]; int a = 100; float b = 20.5; char *c = “Hello”; arr[0] = &a; arr[1] = &b; arr[2] = &c; printf(“Integer: %dn”, *((int *)arr[0])); printf(“Float: %fn”, *((float *)arr[1])); printf(“String: %sn”, *((char **)arr[2])); return 0; } Output When you run this code, it will produce the following output − Integer: 100 Float: 20.500000 String: Hello Application of void Pointers Some of the common applications of void pointers are listed below − The malloc() function is available as a library function in the header file stdlib.h. It dynamically allocates a block of memory during the runtime of a program. Normal declaration of variables causes the memory to be allocated at the compile time. void *malloc(size_t size); Void pointers are used to implement generic functions. The dynamic allocation functions malloc() and calloc() return “void *” type and this feature allows these functions to be used to allocate memory of any data type. The most common application of void pointers is in the implementation of data structures such as linked lists, trees, and queues, i.e., dynamic data structures. Limitations of void Pointer The void pointer has the following limitations − Pointer arithmetic is not possible with void pointer due to its concrete size. It can”t be used as dereferenced. A void pointer cannot work with increment or decrement operators because it doesn”t have a specific type. Print Page Previous Next Advertisements ”;

C – Pointer to Pointer

Pointer to Pointer (Double Pointer) in C ”; Previous Next What is a Double Pointer in C? A pointer to pointer which is also known as a double pointer in C is used to store the address of another pointer. A variable in C that stores the address of another variable is known as a pointer. A pointer variable can store the address of any type including the primary data types, arrays, struct types, etc. Likewise, a pointer can store the address of another pointer too, in which case it is called “pointer to pointer” (also called “double pointer”). A “pointer to a pointer” is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a “pointer to a pointer”, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below − Declaration of Pointer to a Pointer The declaration of a pointer to pointer (double pointer) is similar to the declaration of a pointer, the only difference is that you need to use an additional asterisk (*) before the pointer variable name. Example For example, the following declaration declares a “pointer to a pointer” of type int − int **var; When a target value is indirectly pointed to by a “pointer to a pointer”, accessing that value requires that the asterisk operator be applied twice. Example of Pointer to Pointer (Double Pointer) The following example demonstrates the declaration, initialization, and using pointer to pointer (double pointer) in C: #include <stdio.h> int main() { // An integer variable int a = 100; // Pointer to integer int *ptr = &a; // Pointer to pointer (double pointer) int **dptr = &ptr; printf(“Value of ”a” is : %dn”, a); printf(“Value of ”a” using pointer (ptr) is : %dn”, *ptr); printf(“Value of ”a” using double pointer (dptr) is : %dn”, **dptr); return 0; } Output Value of ”a” is : 100 Value of ”a” using pointer (ptr) is : 100 Value of ”a” using double pointer (dptr) is : 100 How Does a Normal Pointer Work in C? Assume that an integer variable “a” is located at an arbitrary address 1000. Its pointer variable is “b” and the compiler allocates it the address 2000. The following image presents a visual depiction − Let us declare a pointer to int type and store the address of an int variable in it. int a = 10; int *b = &a; The dereference operator fetches the value via the pointer. printf(“a: %d nPointer to ”a” is ”b”: %d nValue at ”b”: %d”, a, b, *b); Example Here is the complete program that shows how a normal pointer works − #include <stdio.h> int main(){ int a = 10; int *b = &a; printf(“a: %d nPointer to ”a” is ”b”: %d nValue at ”b”: %d”, a, b, *b); return 0; } Output It will print the value of int variable, its address, and the value obtained by the dereference pointer − a: 10 Pointer to ”a” is ”b”: 6422036 Value at ”b”: 10 How Does a Double Pointer Work? Let us now declare a pointer that can store the address of “b”, which itself is a pointer to int type written as “int *”. Let”s assume that the compiler also allocates it the address 3000. Hence, “c” is a pointer to a pointer to int, and should be declared as “int **”. int **c = &b; printf(“b: %d nPointer to ”b” is ”c”: %d nValue at b: %dn”, b, c, *c); You get the value of “b” (which is the address of “a”), the value of “c” (which is the address of “b:), and the dereferenced value from “c” (which is the address of “a”) − b: 6422036 Pointer to b is c: 6422024 Value at b: 6422036 Here, “c” is a double pointer. The first asterisk in its declaration points to “b” and the second asterisk in turn points to “a”. So, we can use the double reference pointer to obtain the value of “a” from “c”. printf(“Value of ”a” from ”c”: %d”, **c); This should display the value of ”a” as 10. Example Here is the complete program that shows how a double pointer works − #include <stdio.h> int main(){ int a = 10; int *b = &a; printf(“a: %d nAddress of ”a”: %d nValue at a: %dnn”, a, b, *b); int **c = &b; printf(“b: %d nPointer to ”b” is c: %d nValue at b: %dn”, b, c, *c); printf(“Value of ”a” from ”c”: %d”, **c); return 0; } Output Run the code and check its output − a: 10 Address of ”a”: 1603495332 Value at a: 10 b: 1603495332 Pointer to ”b” is c: 1603495336 Value at b: 1603495332 Value of ”a” from ”c”: 10 A Double Pointer Behaves Just Like a Normal Pointer A “pointer to pointer” or a “double pointer” in C behaves just like a normal pointer. So, the size of a double pointer variable is always equal to a normal pointer. We can check it by applying the sizeof operator to the pointers “b” and “c” in the above program − printf(“Size of b – a normal pointer: %dn”, sizeof(b)); printf(“Size of c – a double pointer: %dn”, sizeof(c)); This shows the equal size of both the pointers − Size of b – a normal pointer: 8 Size of c – a

C – Storage Classes

Storage Classes in C ”; Previous Next C storage classes define the scope (visibility) and lifetime of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program − auto register static extern The auto Storage Class The auto is a default storage class for all variables that are declared inside a function or a block. The keyword “auto“, which is optional, can be used to define local variables. The scope and lifetime of auto variables are within the same block in which they are declared. Example of auto Storage Class The following code statements demonstrate the declaration of an automatic (auto) variable − { int mount; auto int month; } The example above defines two variables with in the same storage class. ”auto” can only be used within functions, i.e., local variables. The register Storage Class The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can”t have the unary ”&” operator applied to it (as it does not have a memory location). The register should only be used for variables that require quick access such as counters. It should also be noted that defining ”register” does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. Example of register Storage Class The following code statement demonstrates the declaration of a register variable − { register int miles; } The static Storage Class The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier may also be applied to global variables. When this is done, it causes that variable”s scope to be restricted to the file in which it is declared. In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class. Example of static Storage Class The following example demonstrates the use of a static storage class in a C program − #include <stdio.h> /* function declaration */ void func(void); static int count = 5; /* global variable */ main(){ while(count–) { func(); } return 0; } /* function definition */ void func(void) { static int i = 5; /* local static variable */ i++; printf(“i is %d and count is %dn”, i, count); } Output When the above code is compiled and executed, it produces the following result − i is 6 and count is 4 i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0 The extern Storage Class The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use ”extern”, the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file. The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below. Example of extern Storage Class The example of an extern storage class may contain two or more files. Here is an example demonstrating the use of an extern storage class in C language − First File: main.c #include <stdio.h> int count; extern void write_extern(); main(){ count = 5; write_extern(); } Second File: support.c #include <stdio.h> extern int count; void write_extern(void) { printf(“Count is %dn”, count); } Here, extern is being used to declare count in the second file, whereas it has its definition in the first file (main.c). Now, compile these two files as follows − $gcc main.c support.c It will produce the executable program a.out. When this program is executed, it will produce the following output − Count is 5 Use of storage classes Storage classes are used to define the scope, visibility, lifetime, and initial (default) value of a variable. Summary of Storage Classes The following table provides a summary of the scope, default value, and lifetime of variables having different storage classes − Storage Class Name Memory Scope, Default Value Lifetime auto Automatic Internal Memory Local Scope, Garbage Value Within the same function or block in which they are declared. register Register Register Local Scope, 0 Within the same function or block in which they are declared. static Static Internal Memory Local Scope, 0 Within the program i.e., as long as program is running. extern External Internal Memory Global Scope, 0 Within the program i.e., as long as program is running. Print Page Previous Next Advertisements ”;

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.

C – Variables

C – Variables ”; Previous Next A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. Why Do We Use Variables in C? A variable in C is a user-assigned name to a certain location in the computer’s memory, which is a collection of a large number of randomly accessible locations capable of holding a single bit. Each location in the memory is identified by a unique address, expressed in binary (or Hexa-decimal for convenience) format. Since it is extremely cumbersome to store and process the data in the memory by referring to their locations in binary form, high-level languages such as C let the locations be identified by user-defined names or variables. Instead of identifying a free memory location and assigning it a value, you can find a suitable mnemonic identifier and assign it a value. The C compiler will choose an appropriate location and bind it to the identifier specified by you. Naming Conventions of C Variables The name of the variable must start with an alphabet (upper or lowercase) or an underscore (_). It may consist of alphabets (upper or lowercase), digits, and underscore characters. No other characters can be a part of the name of a variable in C. Variable names in C are case-sensitive. For example, “age” is not the same as “AGE”. The ANSI standard recognizes a length of 31 characters for a variable name. Although you can choose a name with more characters, only the first 31 will be recognized. Using a descriptive name for a variable, that reflects the value it intends to store is considered to be a good practice. Avoid using very short variable names that might confuse you. C is a statically typed language. Hence, the data type of the variable must be mentioned in the declaration before its name. A variable may be declared inside a function (local variable) or globally. More than one variable of the same type may be declared in a single statement. Example Based on the above set of rules and conventions, here are some valid and invalid variable names: int _num = 5; // valid integer variable float marks = 55.50; // valid float variable char choice = ”0”; // valid char variable // invalid variable name // cannot use “-“ int sub-1 = 35; //invalid; must have data type avg = 50; // invalid; name can be used for // declaration only once in a function int choice = 0; // Valid integer name int sal_of_employee = 20000; // Valid because all are of same type int phy, che, maths; // error because variables of // different types in same statement int sal, float tax; In C, variables can store data belonging to any of the types it recognizes. Hence there are as many number of types of variables as the number of data types in C. Sr.No Type & Description 1 char Typically a single octet(one byte). It is an integer type. 2 int The most natural size of integer for the machine. 3 float A single-precision floating point value. 4 double A double-precision floating point value. 5 void Represents the absence of type. C programming language also allows to define various other types of variables such as Enumeration type, Pointer type, Array type, Structure type, Union type, etc. For this chapter, let us study only basic variable types. Variable Definition in C A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − type variable_list; Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid variable declarations are shown here − int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value; Example: Variable Definition and Initialization Take a look at the following examples: // declaration of d and f extern int d = 3, f = 5; // definition and initializing d and f int d = 3, f = 5; // definition and initializes z byte z = 22; // the variable x has the value ”x” char x = ”x”; For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined. Variable Declaration in C As per the ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed. Although the C99 and C11 standard revisions have removed this stipulation, it is still considered a good programming practice.

C – Booleans

Booleans in C ”; Previous Next Unlike the int, char or float types, the ANSI C standard doesn’t have a built-in or primary Boolean type. A Boolean or bool data generally refers to the one that can hold one of the two binary values: true or false (or yes/no, on/off, etc.). Even if the bool type is not available in C, you can implement the behaviour of Booleans with the help of an enum type. The new versions of C compilers, complying with the C99 standard or later, support the bool type, which has been defined in the header file stdbool.h. Using enum to Implement Boolean Type in C The enum type assigns user-defined identifiers to integral constants. We can define an enumerated type with true and false as the identifiers with the values 1 and 0. Example 1 or any other number that is not 0 represents true, whereas 0 represents false. #include <stdio.h> int main (){ enum bool {false, true}; enum bool x = true; enum bool y = false; printf (“%dn”, x); printf (“%dn”, y); } Output Run the code and check its output − 1 0 typedef enum as BOOL To make it more concise, we can use the typedef keyword to call enum bool by the name BOOL. Example 1 Take a look at the following example − #include <stdio.h> int main(){ typedef enum {false, true} BOOL; BOOL x = true; BOOL y = false; printf (“%dn”, x); printf (“%dn”, y); } Here too, you will get the same output − Output 1 0 Example 2 We can even use the enumerated constants in the decision-making or loop statements − #include <stdio.h> int main(){ typedef enum {false, true} BOOL; int i = 0; while(true){ i++; printf(“%dn”, i); if(i >= 5) break; } return 0; } Output When you run this code, it will produce the following output − 1 2 3 4 5 Boolean Values with #define The #define preprocessor directive is used to define constants. We can use this to define the Boolean constants, FALSE as 0 and TRUE as 1. Example Take a look at the following example − #include <stdio.h> #define FALSE 0 #define TRUE 1 int main(){ printf(“False: %d n True: %d”, FALSE, TRUE); return 0; } Output Run the code and check its output − False: 0 True: 1 Boolean Type in stdbool.h The C99 standard of C has introduced the stdbool.h header file. It contains the definition of bool type, which actually is a typedef alias for _bool type. It also defines the macros true which expands to 1, and false which expands to 0. Example 1 We can use the bool type as follows − #include <stdio.h> #include <stdbool.h> int main(){ bool a = true; bool b = false; printf(“True: %dn”, a); printf(“False: %d”, b); return 0; } Output On executing this code, you will get the following output − True: 1 False: 0 Example 2 We can use bool type variables in logical expressions too, as shown in the following example − #include <stdio.h> #include <stdbool.h> int main(){ bool x; x = 10 > 5; if(x) printf(“x is Truen”); else printf(“x is Falsen”); bool y; int marks = 40; y = marks > 50; if(y) printf(“Result: Passn”); else printf(“Result: Failn”); } Output Run the code and check its output − x is True Result: Fail Example 3 Let us implement a while loop with the help of a bool variable − #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main(void){ bool loop = true; int i = 0; while(loop){ i++; printf(“i: %d n”, i); if (i >= 5) loop = false; } printf(“Loop stopped!n”); return EXIT_SUCCESS; } Output When you run this code, it will produce the following output − i: 1 i: 2 i: 3 i: 4 i: 5 Loop stopped! Print Page Previous Next Advertisements ”;

C – Unions

Unions in C ”; Previous Next Unions in C A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purpose. All the members of a union share the same memory location. Therefore, if we need to use the same memory location for two or more members, then union is the best data type for that. The largest union member defines the size of the union. Defining a Union Union variables are created in same manner as structure variables. The keyword union is used to define unions in C language. Syntax Here is the syntax to define a union in C language − union [union tag]{ member definition; member definition; … member definition; } [one or more union variables]; The “union tag” is optional and each member definition is a normal variable definition, such as “int i;” or “float f;” or any other valid variable definition. At the end of the union”s definition, before the final semicolon, you can specify one or more union variables. Accessing the Union Members To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use the keyword union to define variables of union type. Syntax Here is the syntax to access the members of a union in C language − union_name.member_name; Initialization of Union Members You can initialize the members of the union by assigning the value to them using the assignment (=) operator. Syntax Here is the syntax to initialize members of union − union_variable.member_name = value; Example The following code statement shows to initialization of the member “i” of union “data” − data.i = 10; Examples of Union Example 1 The following example shows how to use unions in a program − #include <stdio.h> #include <string.h> union Data{ int i; float f; char str[20]; }; int main(){ union Data data; data.i = 10; data.f = 220.5; strcpy(data.str, “C Programming”); printf(“data.i: %d n”, data.i); printf(“data.f: %f n”, data.f); printf(“data.str: %s n”, data.str); return 0; } Output When the above code is compiled and executed, it produces the following result − data.i: 1917853763 data.f: 4122360580327794860452759994368.000000 data.str: C Programming Here, we can see that the values of i and f (members of the union) show garbage values because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well. Example 2 Now let”s look at the same example once again where we will use one variable at a time which is the main purpose of having unions − #include <stdio.h> #include <string.h> union Data{ int i; float f; char str[20]; }; int main(){ union Data data; data.i = 10; printf(“data.i: %d n”, data.i); data.f = 220.5; printf(“data.f: %f n”, data.f); strcpy(data.str, “C Programming”); printf(“data.str: %s n”, data.str); return 0; } Output When the above code is compiled and executed, it produces the following result − data.i: 10 data.f: 220.500000 data.str: C Programming Here, the values of all the Union members are getting printed very well because one member is being used at a time. Size of a Union The size of a union is the size of its largest member. For example, if a union contains two members of char and int types. In that case, the size of the union will be the size of int because int is the largest member. You can use the sizeof() operator to get the size of a union. Example In the following example, we are printing the size of a union − #include <stdio.h> // Define a union union Data { int a; float b; char c[20]; }; int main() { union Data data; // Printing the size of the each member of union printf(“Size of a: %lu bytesn”, sizeof(data.a)); printf(“Size of b: %lu bytesn”, sizeof(data.b)); printf(“Size of c: %lu bytesn”, sizeof(data.c)); // Printing the size of the union printf(“Size of union: %lu bytesn”, sizeof(data)); return 0; } Output When you compile and execute the code, it will produce the following output − Size of a: 4 bytes Size of b: 4 bytes Size of c: 20 bytes Size of union: 20 bytes Difference between Structure and Union Both structures and unions are composite data types in C programming. The most significant difference between a structure and a union is the way they store their data. A structure stores each member in separate memory locations, whereas a union stores all its members in the same memory location. Here is a definition of union type called myunion − union myunion{ int a; double b; char c; }; The definition of a union is similar to the definition of a structure. A definition of “struct type mystruct” with the same elements looks like this − struct mystruct{ int a; double b; char c; }; The main difference between a struct and a union is the size of the variables. The compiler allocates the memory to a struct variable, to be able to store the values for all the elements. In mystruct, there are three elements

C – Return Pointer from Functions

Return a Pointer from a Function in C ”; Previous Next In C programming, a function can be defined to have more than one argument, but it can return only one expression to the calling function. A function can return a single value that may be any type of variable, either of a primary type (such as int, float, char, etc.), a pointer to a variable of primary or user−defined type, or a pointer to any variables. Read this chapter to learn the different ways in which a function in a C program returns a pointer. Return a Static Array from a Function in C If a function has a local variable or a local array, then returning a pointer of the local variable is not acceptable because it points to a variable that no longer exists. Note that a local variable ceases to exist as soon as the scope of the function is over. Example 1 The following example shows how you can use a static array inside the called function (arrfunction) and return its pointer back to the main() function. #include <stdio.h> #include <math.h> float * arrfunction(int); int main(){ int x = 100, i; float *arr = arrfunction(x); printf(“Square of %d: %fn”, x, *arr); printf(“Cube of %d: %fn”, x, arr[1]); printf(“Square root of %d: %fn”, x, arr[2]); return 0; } float *arrfunction(int x){ static float arr[3]; arr[0] = pow(x,2); arr[1] = pow(x, 3); arr[2] = pow(x, 0.5); return arr; } Output When you run this code, it will produce the following output − Square of 100: 10000.000000 Cube of 100: 1000000.000000 Square root of 100: 10.000000 Example 2 Now consider the following function which will generate 10 random numbers. They are stored in a static array and return their pointer to the main() function. The array is then traversed in the main() function as follows − #include <stdio.h> #include <time.h> #include <stdlib.h> /* function to generate and return random numbers */ int *getRandom() { static int r[10]; srand((unsigned)time(NULL)); /* set the seed */ for(int i = 0; i < 10; ++i){ r[i] = rand(); } return r; } int main(){ int *p; /* a pointer to an int */ p = getRandom(); for(int i = 0; i < 10; i++) { printf(“*(p + %d): %dn”, i, *(p + i)); } return 0; } Output Run the code and check its output − *(p + 0): 776161014 *(p + 1): 80783871 *(p + 2): 135562290 *(p + 3): 697080154 *(p + 4): 2064569097 *(p + 5): 1933176747 *(p + 6): 653917193 *(p + 7): 2142653666 *(p + 8): 1257588074 *(p + 9): 1257936184 Return a String from a Function in C Using the same approach, you can pass and return a string to a function. A string in C is an array of char type. In the following example, we pass a string with a pointer, manipulate it inside the function, and return it to the main() function. Example Inside the called function, we use the malloc() function to allocate the memory. The passed string is concatenated with the local string before returning. #include <stdio.h> #include <string.h> #include <stdlib.h> char *hellomsg(char *); int main(){ char *name = “TutorialsPoint”; char *arr = hellomsg(name); printf(“%sn”, arr); return 0; } char *hellomsg(char *x){ char *arr = (char *)malloc(50*sizeof(char)); strcpy(arr, “Hello “); strcat(arr, x); return arr; } Output Run the code and check its output − Hello TutorialsPoint Return a Struct Pointer from a Function in C The following example shows how you can return the pointer to a variable of struct type. Here, 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 (pointer) back to the main() function. Example Take a look at the program − #include <stdio.h> #include <string.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 nBreadth: %f nArea: %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 − Length: 10.500000 Breadth: 20.500000 Area: 215.250000 Print Page Previous Next Advertisements ”;