C – Misc Operators ”; Previous Next Besides the main categories of operators (arithmetic, logical, assignment, etc.), C uses the following operators that are equally important. Let us discuss the operators classified under this category. The “&” symbol, already defined in C as the Binary AND Operator copies a bit to the result if it exists in both operands. The “&” symbol is also defined as the address−of operator. The “*” symbol − A well−known arithmetic operator for multiplication, it can also be used as a dereference operator. C uses the “>” symbol, defined as a ternary operator, used to evaluate a conditional expression. In C, the dot “.” symbol is used as the member access operator in connection with a struct or union type. C also uses the arrow “→” symbol as an indirection operator, used especially with the pointer to the struct variable. Operator Description Example sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4. & Returns the address of a variable. &a; returns the actual address of the variable. * Pointer to a variable. *a; ?: Conditional Expression. If Condition is true ? then value X, else value Y . Member access operator var.member −> Access members of a struct variable with pointer ptr −> member; The sizeof Operator in C The sizeof operator is a compile−time unary operator. It is used to compute the size of its operand, which may be a data type or a variable. It returns the size in number of bytes. It can be applied to any data type, float type, or pointer type variables. sizeof(type or var); When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32−bit system can show different output while a 64−bit system can show different of the same data types. Example Here is an example in C language #include <stdio.h> int main(){ int a = 16; printf(“Size of variable a : %dn”,sizeof(a)); printf(“Size of int data type : %dn”,sizeof(int)); printf(“Size of char data type : %dn”,sizeof(char)); printf(“Size of float data type : %dn”,sizeof(float)); printf(“Size of double data type : %dn”,sizeof(double)); return 0; } Output When you run this code, it will produce the following output − Size of variable a: 4 Size of int data type: 4 Size of char data type: 1 Size of float data type: 4 Size of double data type: 8 Address-of Operator in C The “&” operator returns the address of an existing variable. We can assign it to a pointer variable − int a; Assuming that the compiler creates the variable at the address 1000 and “x” at the address 2000, then the address of “a” is stored in “x“. Example Let us understand this with the help of an example. Here, we have declared an int variable. Then, we print its value and address − #include <stdio.h> int main(){ int var = 100; printf(“var: %d address: %d”, var, &var); return 0; } Output Run the code and check its output − var: 100 address: 931055924 The Dereference Operator in C To declare a pointer variable, the following syntax is to be used − type *var; The name of the variable must be prefixed with an asterisk (*). The data type indicates it can store the address of which data type. For example − int *x; In this case, the variable x is meant to store the address of another int variable. float *y; The “y” variable is a pointer that stores the memory location of a float variable. The “&” operator returns the address of an existing variable. We can assign it to the pointer variable − int a; int *x = &a; We can see that the address of this variable (any type of variable for that matter) is an integer. So, if we try to store it in a pointer variable of int type, see what happens − float var1 = 10.55; int *intptr = &var1; The compiler doesn’t accept this, and reports the following error − initialization of ”int *” from incompatible pointer type ”float *” [-Wincompatible-pointer-types] It indicates that the type of a variable and the type of its pointer must be the same. In C, variables have specific data types that define their size and how they store values. Declaring a pointer with a matching type (e.g., “float *”) enforces type compatibility between the pointer and the data it points to. Different data types occupy different amounts of memory in C. For example, an int typically takes 4 bytes, while a float might take 4 or 8 bytes depending on the system. Adding or subtracting integers from pointers moves them in memory based on the size of the data they point to. Hence, we declare the floatptr variable of float * type. Example 1 Take a look at the following example − #include <stdio.h> int main(){ float var1 = 10.55; float *floatptr = &var1; printf(“var1: %f naddress of var1: %d nnfloatptr: %d naddress of floatptr: %d”, var1, &var1, floatptr, &floatptr); return 0; } Output var1: 10.550000 address of var1: 6422044 floatptr: 6422044 address of floatptr: 6422032 Example 2 The
Category: cprogramming
C – Assignment Operators
Assignment Operators in C ”; Previous Next In C language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression. The value to be assigned forms the right-hand operand, whereas the variable to be assigned should be the operand to the left of the “=” symbol, which is defined as a simple assignment operator in C. In addition, C has several augmented assignment operators. The following table lists the assignment operators supported by the C language − Operator Description Example = Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C += Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A -= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C – A *= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A <<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 |= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2 Simple Assignment Operator (=) The = operator is one of the most frequently used operators 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. You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration. You can use a literal, another variable, or an expression in the assignment statement. int x = 10; // declaration with initialization int y; // declaration y = 20; // assignment later int z = x + y; // assign an expression int d = 3, f = 5; // definition and initializing d and f. char x = ”x”; // the variable x has the value ”x”. Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error. In C, the expressions that refer to a memory location are called “lvalue” expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment. On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements − int g = 20; // valid statement 10 = 20; // invalid statement Augmented Assignment Operators In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment. Example 1 For example, the expression “a += b” has the same effect of performing “a + b” first and then assigning the result back to the variable “a”. #include <stdio.h> int main(){ int a = 10; int b = 20; a += b; printf(“a: %d”, a); return 0; } Output Run the code and check its output − a: 30 Example 2 Similarly, the expression “a <<= b” has the same effect of performing “a << b” first and then assigning the result back to the variable “a”. #include <stdio.h> int main(){ int a = 60; int b = 2; a <<= b; printf(“a: %d”, a); return 0; } Output Run the code and check its output − a: 240 Example 3 Here is a C program that demonstrates the use of assignment operators in C − #include <stdio.h> int main(){ int a = 21; int c ; c = a; printf(“Line 1 –
C – Unary Operators
Unary Operators in C ”; Previous Next While most of the operators in C are binary in nature, there are a few unary operators as well. An operator is said to be unary if it takes just a single operand, unlike a binary operator which needs two operands. Some operators in C are binary as well as unary in their usage. Examples of unary operators in C include ++, —, !, etc. The Increment Operator in C The increment operator (++) adds 1 to the value of its operand variable and assigns it back to the variable. The statement a++ is equivalent to writing “a = a + 1.” The “++” operator can appear before or after the operand and it will have the same effect. Hence, a++ is equivalent to ++a. However, when the increment operator appears along with other operators in an expression, its effect is not the same. The precedence of “prefix ++” is more than “postfix ++”. Hence, “b = a++;” is not the same as “b = ++a;“ In the former case, “a” is assigned to “b” before the incrementation; while in the latter case, the incrementation is performed before the assignment. The Decrement Operator in C The decrement operator (–) subtracts 1 from the value of its operand variable and assigns it back to the variable. The statement “a–;” is equivalent to writing “a = a – 1;“ The “–” operator can appear before or after the operand and in either case, it will have the same effect. Hence, “a–” is equivalent to “–a“. However, when the decrement operator appears along with other operators in an expression, its effect is not the same. The precedence of “prefix –” is more than “postfix –“. Hence, “b = a–” is not the same as “b = –a“. In the former case, “a” is assigned to “b” before the decrementation; while in the latter case, the decrementation is performed before the assignment. The Unary “+” Operator in C The “+” and “–” operators are well known as binary addition and subtraction operators. However, they can also be used in unary fashion. When used as unary, they are prefixed to the operand variable. The “+” operator is present implicitly whenever a positive value is assigned to any numeric variable. The statement “int x = 5;” is same as “int x = +5;“. The same logic applies to float and char variable too. Example Take a look at the following example − #include <stdio.h> int main(){ char x = ”A”; char y = +x; float a = 1.55; float b = +a; printf (“x: %c y: %cn”, x,y); printf (“a: %f y: %fn”, a,b); return 0; } Output When you run this code, it will produce the following output − x: A y: A a: 1.550000 y: 1.550000 The Unary “−” Operator in C The “−” symbol, that normally represents the subtraction operator, also acts the unary negation operator in C. The following code shows how you can use the unary negation operator in C. Example In this code, the unary negation operator returns the negative value of “x” and assigns the same to another variable “y”. #include <stdio.h> int main(){ int x = 5; int y = -x; printf(“x: %d y: %dn”, x, y); return 0; } Output Run the code and check its output − x: 5 y: -5 The Address-of Operator (&) in C We use the & symbol in C as the binary AND operator. However, we also use the same & symbol in unary manner as the “address-of” operator. Example The & operator returns the memory address of its variable operand. Take a look at the following example − #include <stdio.h> int main(){ char x = ”A”; printf (“Address of x: %dn”, &x); return 0; } Output Run the code and check its output − Address of x: 6422047 Note: The C compiler assigns a random memory address whenever a variable is declared. Hence, the result may vary every time the address is printed. The format specifier %p is used to get a hexadecimal representation of the memory address. char x = ”A”; printf (“Address of x: %pn”, &x); This prints the address of “x” in hexadecimal format − Address of x: 000000000061FE1F The address of a variable is usually stored in a “pointer variable”. The pointer variable is declared with a “*” prefix. In the code snippet below, “x” is a normal integer variable while “y” is a pointer variable. int x = 10; int *y = &x; The Dereference Operator (*) in C We normally use the “*” symbol as the multiplication operator. However, it is also used as the “dereference operator” in C. When you want to store the memory address of a variable, the variable should be declared with an asterisk (*) prefixed to it. int x = 10; int *y = &x; Here the variable “y” stores the address of “x”, hence “y” acts as a pointer to “x”. To access the value of “x” with the help of its pointer, use the dereference operator (*). Example 1 Take a look at the following example − #include <stdio.h> int main(){ int x = 10; int *y = &x; printf (“x: %d Address of x: %dn”, x, &x); printf(“Value at x with Dereference: %d”, *y); return 0; } Output Run the code and check its output − x: 10 Address of x: 6422036 Value at x with Dereference: 10
C – Arithmetic Operators
Arithmetic Operators in C ”; Previous Next Arithmetic operators in C are certain special symbols, predefined to perform arithmetic operations. We are familiar with the basic arithmetic operations − addition, subtraction, multiplication and division. C is a computational language, so these operators are essential in performing a computerised process. In addition to the above operations assigned to the four symbols +, −, *, and / respectively, C has another arithmetic operator called the modulo operator for which we use the %symbol. The following table lists the arithmetic operators in C − Operator Description + Adds two operands. − Subtracts second operand from the first. * Multiplies both operands. / Divides numerator by denominator. % Modulus Operator and remainder of after an integer division. ++ Increment operator increases the integer value by one. — Decrement operator decreases the integer value by one. The ++ and — operators are also listed in the above table. We shall learn about increment and decrement operators in a separate chapter. Example: Arithmetic Operators in C The following example demonstrates how to use these arithmetic operators in a C program − #include <stdio.h> int main(){ int op1 = 10; int op2 = 3; printf(“Operand1: %d Operand2: %d nn”, op1, op2); printf(“Addition of op1 and op2: %dn”, op1 + op2); printf(“Subtraction of op2 from op1: %dn”, op1 – op2); printf(“Multiplication of op1 and op2: %dn”, op1 * op2); printf(“Division of op1 by op2: %dn”, op1/op2); return 0; } Output When you run this code, it will produce the following output − Operand1: 10 Operand2: 3 Addition of op1 and op2: 13 Subtraction of op2 from op1: 7 Multiplication of op1 and op2: 30 Division of op1 by op2: 3 Type Casting in C The first three results are as expected, but the result of division is not. You expect 10/3 to be a fractional number (3.333333). Is it because we used the %d format specifier to print the outcome of the division? If we change the last line of the code as follows − printf(“Division of op1 by op2: %fn”, op1/op2); Now the outcome of the division operation will be “0.000000”, which is even more surprising. The reason why C behaves like this is because the division of an integer with another integer always returns an integer. To obtain floating-point division, at least one operand must be a float, or you need to use the typecast operator to change one of the integer operands to float. Now, change the last printf statement of the given program as follows − printf(“Division of op1 by op2: %fn”, (float)op1/op2); When you run run the code again after making this change, it will show the correct division − Division of op1 by op2: 3.333333 Note: If you use %d format specifier for a floating-point expression, it will always result in “0”. Example The result of arithmetic operations with at least one float (or double) operand is always float. Take a look at the following example − #include <stdio.h> int main(){ int op1 = 10; float op2 = 2.5; printf(“Operand1: %d Operand2: %fn”, op1, op2); printf(“Addition of op1 and op2: %fn”, op1 + op2); printf(“Subtraction of op2 from op1: %fn”, op1 – op2); printf(“Multiplication of op1 and op2: %fn”, op1 * op2); printf(“Division of op1 by op2: %fn”, op1/op2); return 0; } Output Run the code and check its output − Operand1: 10 Operand2: 2.500000 Addition of op1 and op2: 12.500000 Subtraction of op2 from op1: 7.500000 Multiplication of op1 and op2: 25.000000 Division of op1 by op2: 4.000000 Arithmetic Operations with char Data Type In C, char data type is a subset of int type. Hence, we can perform arithmetic operations with char operands. Example The following example shows how you can perform arithmetic operations with two operands out of which one is a “char” type − #include <stdio.h> int main(){ char op1 = ”F”; int op2 = 3; printf(“operand1: %c operand2: %dn”, op1, op2); printf(“Addition of op1 and op2: %dn”, op1 + op2); printf(“Subtraction of op2 from op1: %dn”, op1 – op2); printf(“Multiplication of op1 and op2: %dn”, op1 * op2); printf(“Division of op1 by op2: %dn”, op1/op2); return 0; } Output Run the code and check its output − operand1: F operand2: 3 Addition of op1 and op2: 73 Subtraction of op2 from op1: 67 Multiplication of op1 and op2: 210 Division of op1 by op2: 23 Since a char data type is a subset of int, the %c format specifier returns the ASCII character associated with an integer returned by the %d specifier. If any arithmetic operation between two char operands results in an integer beyond the range of char, the %c specifier displays blank. Modulo Operator in C The modulo operator (%) returns the remainder of a division operation. Example Take a look at the following example − #include <stdio.h> int main(){ int op1 = 10; int op2 = 3; printf(“Operand1: %d Operand2: %dn”, op1, op2); printf(“Modulo of op1 and op2: %dn”, op1%op2); return 0; } Output Run the code and check its output − Operand1: 10 Operand2: 3 Modulo of op1 and op2: 1 The modulo operator needs both the operands of int type. If not, the compiler gives a type mismatch error. For example, change the data type of “op1” to float in the above code and run
C – Literals
C – Literals ”; Previous Next The term “literal” in computer programming terminology refers to a textual representation of a value to be assigned to a variable. In C, you can assign a value to a variable in two ways − Using literal representation Using an expression The initialization of a variable in C is done as follows − int x = 10; On the other hand, an indirect initialization of a variable by assigning it the result of an expression is as follows − int x = 10; int y = x*2; In the first case, 10 is an integer literal assigned to “x”. In the second case, the result of “x*2” expression is assigned to “y”. A literal is thus a value of a certain data type represented directly into the source code. Normally, literals are used to set a value of a variable. On their own, literals don’t form any of the programming element. Different notations are used to represent the values of different data types. Integer Literals in C In the above example, 10 is an integer literal. A positive or negative whole number represented with digits 0 to 9, without a fractional part is a decimal integer literal. It must be within the acceptable range for the given OS platform. Following examples assign decimal literals to int variables − int x = 200; int y = -50; An integer literal can also have a suffix that is a combination of “U” and “L”, for “unsigned” and “long”, respectively. The suffix can be uppercase or lowercase and can be in any order. int c = 89U; long int d = 99998L; C allows you to represent an integer in octal and hexadecimal number systems. For a literal representation of an octal, prefix the number with 0 (ensure that the number uses octal digits only, from 0 to 7). For a hexadecimal literal, prefix the number with 0x or 0X. The hexadecimal number must have 0 to 9, and A to F (or a to f) symbols. Example Take a look at the following example − #include <stdio.h> int main(){ int oct = 025; int hex = 0xa1; printf(“Octal to decimal: %dn”, oct); printf(“Hexadecimal to decimal: %dn”, hex); } Output On running this code, you will get the following output − Octal to decimal: 21 Hexadecimal to decimal: 161 Modern C compilers also let you represent an integer as a binary number, for which you need to add a 0b prefix. Example Take a look at the following example − #include <stdio.h> int main(){ int x = 0b00010000; printf(“binary to decimal: %d”, x); } Output Run the code and check its output − binary to decimal: 16 Here are some examples of integer literals − 212 /* valid */ 215u /* valid */ 0xFeeL /* valid */ 078 /* invalid: 8 is not an octal digit */ 032UU /* invalid: cannot repeat a suffix */ Here are some other examples of various types of integer literals − 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ Floating-point Literals in C A floating-point literal in C is a real number with an integer part and a fractional part within the range acceptable to the compiler in use, and represented in digits, decimal point with an optional exponent symbol (e or E). A floating point literal is generally used for initializing or setting the value of a float or a double variable in C. Example The following assignment examples use floating point literals with a decimal point separating the integer and the fractional part − #include <stdio.h> int main(){ float x = 10.55; float y = -1.333; printf(“x and y are: %f, %f”, x, y); } Output You will get the following output − x and y are: 10.550000, -1.333000 Floating point literals with a high degree of precision can be stated with the exponentiation symbol “e” or “E”. This is called the scientific notation of a float literal. While representing decimal form, you must include the decimal point, the exponent, or both. While representing exponential form, you must include the integer part, the fractional part, or both. Example Take a look at the following example − #include <stdio.h> int main(){ float x = 100E+4; float y = -1.3E-03; printf(“x: %fn”, x); printf(“y: %fn”, y); } Output When you run this code, it will produce the following output − x: 1000000.000000 y: -0.001300 Here are some examples of floating-point literals − 3.14159 /* valid */ 314159E-5L /* valid */ 510E /* invalid: incomplete exponent */ 210f /* invalid: no decimal or exponent */ .e55 /* invalid: missing integer or fraction */ Character Literals in C A character literal in C is a single character enclosed within single quote symbols. Note that C recognizes straight quotes only. Hence, use ” to form a character literal and not ‘). Here is an example − char x = ”I”; Character literals are generally assigned to a char variable that occupies a single byte. Using the %c format specifier outputs the character. Use %d and you’ll obtain the ASCII value of the character. Example Take a look at the following example − #include <stdio.h> int main(){ char x = ”I”; printf(“x: %cn”, x); printf(“x: %dn”, x); } Output Run the code and check
C – Bitwise Operators
Bitwise Operators in C ”; Previous Next Bitwise operators in C allow low-level manipulation of data stored in computer’s memory. Bitwise operators contrast with logical operators in C. For example, the logical AND operator (&&) performs AND operation on two Boolean expressions, while the bitwise AND operator (&) performs the AND operation on each corresponding bit of the two operands. For the three logical operators &&, ||, and !, the corresponding bitwise operators in C are &, | and ~. Additionally, the symbols ^ (XOR), << (left shift) and >> (right shift) are the other bitwise operators. Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) | Binary OR Operator copies a bit if it exists in either operand. (A | B) ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) ~ Binary One”s Complement Operator is unary and has the effect of ”flipping” bits. (~A << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 Even though these operators work on individual bits, they need the operands in the form C data types or variables only, as a variable occupies a specific number of bytes in the memory. Bitwise AND Operator (&) in C The bitwise AND (&) operator performs as per the following truth table − bit a bit b a & b 0 0 0 0 1 0 1 0 0 1 1 1 Bitwise binary AND performs logical operation on the bits in each position of a number in its binary form. Assuming that the two int variables “a” and “b” have the values 60 (equivalent to 0011 1100 in binary) and 13 (equivalent to 0000 1101 in binary), the “a & b” operation results in 13, as per the bitwise ANDing of their corresponding bits illustrated below − 0011 1100 & 0000 1101 ——— = 0000 1100 The binary number 00001100 corresponds to 12 in decimal. Bitwise OR (|) Operator The bitwise OR (|) operator performs as per the following truth table − bit a bit b a | b 0 0 0 0 1 1 1 0 1 1 1 1 Bitwise binary OR performs logical operation on the bits in each position of a number in its binary form. Assuming that the two int variables “a” and “b” have the values 60 (equivalent to 0011 1100 in binary) and 13 (equivalent to 0000 1101 in binary), then “a | b” results in 61, as per the bitwise OR of their corresponding bits illustrated below − 0011 1100 | 0000 1101 ——— = 0011 1101 The binary number 00111101 corresponds to 61 in decimal. Bitwise XOR (^) Operator The bitwise XOR (^) operator performs as per the following truth table − bit a bit b a ^ b 0 0 0 0 1 1 1 0 1 1 1 0 Bitwise binary XOR performs logical operation on the bits in each position of a number in its binary form. The XOR operation is called “exclusive OR”. Note: The result of XOR is 1 if and only if one of the operands is 1. Unlike OR, if both bits are 1, XOR results in 0. Assuming that the two int variables “a” and “b” have the values 60 (equivalent to 0011 1100 in binary) and 13 (equivalent to 0000 1101 in binary), the “a ^ b” operation results in 49, as per the bitwise XOR of their corresponding bits illustrated below − 0011 1100 ^ 0000 1101 ——— = 0011 0001 The binary number 00110001 corresponds to 49 in decimal. The Left Shift (<<) Operator The left shift operator is represented by the << symbol. It shifts each bit in its left-hand operand to the left by the number of positions indicated by the right-hand operand. Any blank spaces generated while shifting are filled up by zeroes. Assuming that the int variable “a” has the value 60 (equivalent to 0011 1100 in binary), the “a << 2” operation results in 240, as per the bitwise left-shift of its corresponding bits illustrated below − 0011 1100 << 2 = 1111 0000 The binary number 11110000 corresponds to 240 in decimal. The Right Shift (>>) Operator The right shift operator is represented by the >> symbol. It shifts each bit in its left-hand operand to the right by the number of positions indicated by the right-hand operand. Any blank spaces generated while shifting are filled up by zeroes. Assuming that the int variable a has the value 60 (equivalent to 0011 1100 in binary), the “a >> 2” operation results in 15, as per the
C – Constants
C – Constants ”; Previous Next A constant in C is a user-assigned name to a location in the memory, whose value cannot be modified once declared. This is in contrast to a variable in C, which is also a named memory location, however whose value may be changed during the course of the code. Instead of repeatedly using hard-coded values in a program, it is advised to define a constant and use it. Constants in a C program are usually employed to refer to a value which may be error-prone if it is to be used repetitively in the program, at the same time its value is not likely to change. For example, the value of mathematical constant PI is a high-precision floating point number 3.14159265359, and if it is likely to appear frequently, it is declared as a constant and used by its name. We may consider a constant in C as a read-only variable, as its value can only be used subsequently but cannot be modified. You can declare a constant in C program with either of the following two ways − Using the const Keyword Using the #define Directive Let”s understand these two ways of declaring a constant in C. Defining a Constant Using the const Keyword The syntax of declaring a constant is as follows − const type NAME = val; For example, const float PI = 3.14159265359; We can now use PI in any expression, as we would use any variable. Example Take a look at the following example − #include <stdio.h> int main(){ const float PI = 3.14159265359; float radius = 5; float area = PI*radius*radius; printf (“area: %f”, area); return 0; } Output On running this code, you will get following output − area: 78.539818 However, changing the value of a constant is prohibited. The following statement gives a compiler error − const float PI = 3.14159265359; PI=22/7; Here, you will get the following error message − error: assignment of read-only variable ”PI” In case of variables, you can declare a variable and assign it a value later on in the program, however you cannot follow the same process in case of a constant. You can declare a constant in C without assigning it a value. But when you try to assign it a value afterwords, then the compiler will throw an error. const float PI; PI = 3.14159265359; Here, you will get this error message − error: assignment of read-only variable ”PI” Note: “sizeof” returns “size_t”. The type of unsigned integer of “size_t” can vary depending on platform. And, it may not be long unsigned int everywhere. In such cases, we use “%zu” for the format string instead of “%d”. This is because the compiler assigns a random garbage value at the time of declaration, which you cannot change afterwards. Hence, you must declare and initialize the constant at once. A constant in C can be of any of the data types including primary data types such as int, float, char, and derived data types such as struct. Defining a Constant Using the #define Directive Using the #define preprocessor directive is also an effective method to define a constant. Here is its syntax − #define name = value Take a look at the following example: #define PI = 3.14159265359 Although the constant so defined can also be used in any expression (just as the one with the const keyword), there is a difference between the two. The constants created by the #define directive are not handled by the compiler. Instead, they behave as macros, whose values are substituted at the runtime. The other notable difference is that you need not mention the data type of the value to be assigned to the constant when using the #define directive. Example: Define a Constant Using the #define Given below is another example of a constant defined using the #define directive − #include <stdio.h> #define LENGTH 10 #define WIDTH 5 #define NEWLINE ”n” int main() { int area; area = LENGTH * WIDTH; printf(“length: %d width: %d”, LENGTH, WIDTH); printf(“%c”, NEWLINE); printf(“value of area : %d”, area); return 0; } Output Upon running this code, you will get the following output − length: 10 width: 5 value of area : 50 Since a constant is also an identifier in C, it follows all the rules of forming an identifier. Identifiers in C are case-sensitive. Hence the convention followed while defining a constant in C is that it uses uppercase characters, however it is not mandatory. Changing the Value of a Constant By definition, constants are immutable. Why would you change the value of a constant in the first place? We use constants whose value is supposed to remain unchanged. To be able to change the value, we would define a variable rather than a constant. We have seen that it is not possible to assign a new value to an already defined constant. However, there exists a workaround with which a new value can be assigned to a constant. The technique uses the concept of pointers in C. A Pointer is a variable that stores the address of another variable. Since it is a variable, its value can be changed. Moreover, this change reflects in the original variable. Example: Change the Value of a Constant The following code demonstrates how to change the value of a constant with the pointer mechanism − #include <stdio.h> int main(){ const int x = 10; printf(“Initial Value of Constant: %dn”, x); // y is a pointer to constant
C – Escape sequences
Escape Sequence in C ”; Previous Next Escape Sequence in C An escape sequence in C is a literal made up of more than one character put inside single quotes. Normally, a character literal consists of only a single character inside single quotes. However, the escape sequence attaches a special meaning to the character that appears after a backslash character (). The symbol causes the compiler to escape out of the string and provide meaning attached to the character following it. Look at n as an example. When put inside a string, the n acts as a newline character, generating the effect of pressing the Enter key. The following statement − printf(” Hello n World “); Will produce this output − Hello World The new line is an unprintable character. The n escape sequence is useful to generate its effect. Similarly, the escape sequence t is equivalent to pressing the Tab key on the keyboard. An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly. All Escape Sequences in C In C, all escape sequences consist of two or more characters, the first of which is the backslash (called the “Escape character”); the remaining characters have an interpretation of the escape sequence as per the following table. Here is a list of escape sequences available in C − Escape sequence Meaning \ character ” ” character “ ” character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab ooo Octal number of one to three digits xhh . . . Hexadecimal number of one or more digits Let us understand how these escape sequences work with the help of a set of examples. Newline Escape Sequence (n) The newline character, represented by the escape sequence n in C, is used to insert the effect of carriage return on the output screen. You would use this escape sequence to print text in separate lines and improve the readability of output. Example Take a look at the following example − #include <stdio.h> int main(){ printf(“Hello.nGood morning.nMy name is Ravi”); } Output On running this code, you will get the following output − Hello. Good morning. My name is Ravi Tab Escape Sequence (t) The tab character (t) represents the Tab key on the keyboard. When the tab character is encountered in a string, it causes the cursor to move to the next horizontal tab stop. Horizontal tab stops are usually set at intervals of eight characters. Example Take a look at the following example − #include <stdio.h> int main(){ printf(“Name:tRavitMarks:t50”); } Output Run the code and check its output − Name: Ravi Marks: 50 Backslash Escape Sequence (\) To add backslash character itself as a part of a string, it must precede by another backslash. First backslash escapes out of the string, and the second one takes the effect. Example Take a look at the following example − #include <stdio.h> int main(){ printf(“Directory in Windows: C:\users\user”); } Output On running this code, you will get the following output − Directory in Windows: C:usersuser Double and Single Quotes Escape Sequences (” and ”) These characters have a special meaning in C since ” and ” symbols are used for the representation of a character literal and a string literal respectively. Hence, to treat these characters as a part of the string, they must be escaped with an additional backslash preceding them. Example Take a look at the following example − #include <stdio.h> int main(){ printf(“Welcome to “TutorialsPoint”n”); printf (“”Welcome” to TutorialsPoint”); } Output Run the code and check its output − Welcome to “TutorialsPoint” ”Welcome” to TutorialsPoint Backspace Escape Sequence (b) The escape sequence “b”, represents the backspace character. It is used erase a character or a specific portion of a text that has already been printed on the screen. Example Check the following example code − #include <stdio.h> int main(){ printf(“Welcome tob TutorialsPoint”); } Output Run the code and check its output − Welcome t TutorialsPoint Note that o from to has been erased. C also has a r escape sequence. The newline escape sequence (n) moves the cursor to the beginning of the next line, while the carriage return escape sequence (r) moves the cursor to the beginning of the current line. Octal Number Escape Sequence (ooo) This escape sequence is used for Octal numbers of one to three digits. An octal escape sequence is a backslash followed by one, two, or three octal digits (0-7). It matches a character in the target sequence with the value specified by those digits. Example Take a look at the following example − #include <stdio.h> int main(){ printf(“%c”, ”141”); return 0; } Output When you run this code, it will produce the following output − a Hexadecimal Number Escape Sequence (xhh) A hexadecimal escape sequence is a backslash followed by the
C – Preprocessor Operators
Preprocessor Operators in C ”; Previous Next Preprocessor operators are special symbol(s) that are used in the context of the #define directive. These operators are also called preprocessor-specific operators. In C, a set of preprocessor operators have been defined, each with an important operation attached with it. In this chapter, we will explain the different types of preprocessor operators used in C. The following preprocessor operators are implemented by most of the modern C compilers − Operator Action Continuation operator (/) Used to continue a macro that is too long for a single line. Stringizing operator (#) Causes the corresponding actual argument to be enclosed in double quotation marks Token-pasting operator (##) Allows tokens used as actual arguments to be concatenated to form other tokens defined operator Simplifies the writing of compound expressions in certain macro directives Let us now discuss in detail about each of these preprocessor operators. Continuation Operator (/) This operator is used where the macro is quite complex, and spreads over multiple lines. In case of a complex logic inside macro expansion, you’ll need to break the line and write code that spreads over more than one lines. In such cases macro continuation operator is very helpful. Example 1: Preprocessor Continuation Operator (/) In the example below, we are writing a part of the macro in the next line, so we are making use of macro continuation preprocessor operator (). #include <stdio.h> #define message() { printf(“TutorialsPoint Library containsn”); printf(“High quality Programming Tutorials”); } int main() { message(); return 0; } Output When you run this code, it will produce the following output − TutorialsPoint Library contains High quality Programming Tutorials Example 2: Preprocessor Continuation Operator (/) In the following example, the macro definition involves evaluation of a switch case statement, hence it spreads over multiple lines, requiring the macro continuation character. #include <stdio.h> #define SHAPE(x) switch(x) { case 1: printf(“1. CIRCLEn”); break; case 2: printf(“2. RECTANGLEn”); break; case 3: printf(“3. SQUAREn”); break; default: printf(“default. LINEn”); } int main() { SHAPE(1); SHAPE(2); SHAPE(3); SHAPE(0); return 0; } Output When you run this code, it will produce the following output − 1. CIRCLE 2. RECTANGLE 3. SQUARE default. LINE Stringizing Operator (#) Sometimes you may want to convert a macro argument into a string constant. The number-sign or “stringizing” operator (#) converts macro parameters to string literals without expanding the parameter definition. This operator may be used only in a macro having a specified argument or parameter list. Example 1: Stringizing Operator Take a look at the following example − #include <stdio.h> #define stringize(x) printf(#x “n”) int main() { stringize(Welcome To TutorialsPoint); stringize(“The Largest Tutorials Library”); stringize(“Having video and Text Tutorials on Programming Languages”); } Output When you run this code, it will produce the following output − Welcome To TutorialsPoint “The Largest Tutorials Library” “Having video and Text Tutorials on Programming Languages” Example 2: Stringizing Operator The following code shows how you can use the stringize operator to convert some text into string without using any quotes. #include <stdio.h> #define STR_PRINT(x) #x main() { printf(STR_PRINT(This is a string without double quotes)); } Output Run the code and check its output − This is a string without double quotes Token Pasting Operator (##) The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator. It is often useful to merge two tokens into one while expanding macros. When a macro is expanded, the two tokens on either side of each “##” operator are combined into a single token, which then replaces the “##” and the two original tokens in the macro expansion. Example 1: Token Pasting Operator (##) Take a look at the following example − #include <stdio.h> #define PASTE(arg1,arg2) arg1##arg2 main() { int value_1 = 1000; printf(“value_1 = %dn”, PASTE(value_,1)); } Output When you run this code, it will produce the following output − value_1 = 1000 Example 2: Token Pasting Operator (##) In the example below, we pass two arguments to the macro. #include <stdio.h> #define TOKENS(X, Y) X##Y int main() { printf(“value1: %dn”,TOKENS(12,20)); printf(“value2: %dn”,TOKENS(12,20)+10); return 0; } Output When you run this code, it will produce the following output − value1: 1220 value2: 1230 The defined Operator The defined preprocessor operator can only be used as a part of #if and #elif directives. The syntax of defined operator is as follows − #if defined(macro1) // code #elif defined(macro2) // code #endif It is used in constant expressions to determine if an identifier is defined. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). Example 1: defined Operator In this example, the defined operator is used to check if the DEBUG macro is defined. If it is, the program prints “DEBUG mode is on.” Otherwise, it prints “DEBUG mode is off.” #include <stdio.h> #define DEBUG 1 int main() { #if defined(DEBUG) printf(“DEBUG mode is on.n”); #else printf(“DEBUG mode is off.n”); #endif return 0; } Output Run the code and check its output − DEBUG mode is on. Example 2: defined Operator The following code checks if the square macro has been already defined, and if so, expands it with the given value of “x”
C – Keywords
C – Keywords ”; Previous Next Keywords are those predefined words that have special meaning in the compiler and they cannot be used for any other purpose. As per the C99 standard, C language has 32 keywords. Keywords cannot be used as identifiers. The following table has the list of all keywords (reserved words) available in the C language: auto double int struct break else long switch case enum register typedef char extern return union continue for signed void do if static while default goto sizeof volatile const float short unsigned All the keywords in C have lowercase alphabets, although the keywords that have been newly added in C, do have uppercase alphabets in them. C is a case-sensitive language. Hence, int is a keyword but INT, or Int are not recognized as a keyword. The new keywords introduced from C99 onwards start with an underscore character. The compiler checks the source code for the correctness of the syntax of all the keywords and then translates it into the machine code. Example of C Keywords In the following program, we are using a keyword as an identifier i.e., as the name of the user-defined function, that will cause a compilation error. #include <stdio.h> void register(int, int); int main () { /* variable definition: */ int a=5, b=7; register(a,b); return 0; } void register(int a, int b) { printf(“%d”, a+b); } Errors main.c:3:15: error: expected identifier or ”(” before ”int” 3 | void register(int, int); | ^~~ main.c: In function ”main”: main.c:8:14: error: expected ”)” before ”,” token 8 | register(a,b); | ^ | ) main.c: At top level: main.c:12:15: error: expected identifier or ”(” before ”int” 12 | void register(int a, int b) | ^ The reason for the errors is that we are using a keyword register as the name of a user-defined function, which is not allowed. The ANSI C version has 32 keywords. These keywords are the basic element of the program logic. These keywords can be broadly classified in following types − Primary Data types User defined types Storage types Conditionals Loops and loop controls Others Let us discuss the keywords in each category. Primary Types C Keywords These keywords are used for variable declaration. C is a statically type language, the variable to be used must be declared. Variables in C are declared with the following keywords: int Declares an integer variable long Declares a long integer variable short Declares a short integer variable signed Declares a signed variable double Declares a double-precision variable char Declares a character variable float Declares a floating-point variable unsigned Declares an unsigned variable void Specifies a void return type User-defined Types C Keywords C language allows you to define new data types as per requirement. The user defined type has one or more elements of primary type. The following keywords are provided for user defined data types − struct Declares a structure type typedef Creates a new data type union Declares a union type enum Declares an enumeration type Storage Types C Keywords The following set of keywords are called storage specifiers. They indicate the location where in the memory the variables stored. Default storage type of a variable is auto, although you can ask the compiler to form a variable with specific storage properties. auto Specifies automatic storage class extern Declares a variable or function static Specifies static storage class register Specifies register storage class Conditionals C Keywords The following set of keywords help you to put conditional logic in the program. The conditional logic expressed with if and else keywords provides two alternative actions for a condition. For multi-way branching, use switch – case construct. In C, the jump operation in an assembler is implemented by the goto keyword. goto Jumps to a labeled statement if Starts an if statement else Executes when the if condition is false case Labels a statement within a switch switch Starts a switch statement default Specifies default statement in switch Loops and Loop Control C Keywords Repetition or iteration is an essential aspect of the algorithm. C provides different alternatives for forming a loop, and keywords for controlling the behaviour of the loop. Each of the keywords let you form a loop of different characteristics and usage. For Starts a for-loop do Starts a do-while loop while starts a while loop continue Skips an iteration of a loop break Terminates a loop or switch statement Other C Keywords The following miscellaneous keywords are also extremely important: const Specifies a constant value Sizeof Determines the size of a data type Volatile compiler that the value of the variable may change at any time In C99 version, five more keywords were added − _Bool _Complex _Imaginary inline In C11, seven more keywords have been added _Alignas _Alignof _Atomic