Author: saqibkhan

  • The sizeof Operator

    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 a data type, it simply returns the amount of memory allocated to that data type. The outputs can be different on different machines, for example, a 32-bit system can show a different output as compared to a 64-bit system.

    Example 1: Using the sizeof Operator in C

    Take a look at the following example. It highlights how you can use the sizeof operator in a C program −

    #include <stdio.h>intmain(){int a =16;printf("Size of variable a: %d \n",sizeof(a));printf("Size of int data type: %d \n",sizeof(int));printf("Size of char data type: %d \n",sizeof(char));printf("Size of float data type: %d \n",sizeof(float));printf("Size of double data type: %d \n",sizeof(double));return0;}

    Output

    On running this code, you will get 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
    

    Example 2: Using sizeof with Struct

    In this example, we declare a struct type and find the size of the struct type variable.

    #include <stdio.h>structemployee{char name[10];int age;double percent;};intmain(){structemployee e1 ={"Raghav",25,78.90};printf("Size of employee variable: %d\n",sizeof(e1));return0;}

    Output

    Run the code and check its output −

    Size of employee variable: 24
    

    Example 3: Using sizeof with Array

    In the following code, we have declared an array of 10 int values. Applying the sizeof operator on the array variable returns 40. This is because the size of an int is 4 bytes.

    #include <stdio.h>intmain(){int arr[]={1,2,3,4,5,6,7,8,9,10};printf("Size of arr: %d\n",sizeof(arr));}

    Output

    Run the code and check its output −

    Size of arr: 40
    

    Example 4: Using sizeof to Find the Length of an Array

    In C, we dont have a function that returns the number of elements in a numeric array (we can get the number of characters in a string using the strlen() function). For this purpose, we can use the sizeof() operator.

    We first find the size of the array and then divide it by the size of its data type.

    #include <stdio.h>intmain(){int arr[]={1,2,3,4,5,6,7,8,9,10};int y =sizeof(arr)/sizeof(int);printf("No of elements in arr: %d\n", y);}

    Output

    When you run this code, it will produce the following output −

    No of elements in arr: 10
    

    Example 5: Using sizeof in Dynamic Memory Allocation

    The sizeof operator is used to compute the memory block to be dynamically allocated with the malloc() and calloc() functions.

    The malloc() function is used with the following syntax −

    type *ptr =(type *)malloc(sizeof(type)*number);

    The following statement allocates a block of 10 integers and stores its address in the pointer −

    int*ptr =(int*)malloc(sizeof(int)*10);

    When the sizeof() is used with an expression, it returns the size of the expression. Here is an example.

    #include <stdio.h>intmain(){char a ='S';double b =4.65;printf("Size of variable a: %d\n",sizeof(a));printf("Size of an expression: %d\n",sizeof(a+b));int s =(int)(a+b);printf("Size of explicitly converted expression: %d\n",sizeof(s));return0;}

    Output

    Run the code and check its output −

    Size of variable a: 1
    Size of an expression: 8
    Size of explicitly converted expression: 4
    

    Example 6: The Size of a Pointer in C

    The sizeof() operator returns the same value irrespective of the type. This includes the pointer of a built−in type, a derived type, or a double pointer.

    #include <stdio.h>intmain(){printf("Size of int data type: %d \n",sizeof(int*));printf("Size of char data type: %d \n",sizeof(char*));printf("Size of float data type: %d \n",sizeof(float*));printf("Size of double data type: %d \n",sizeof(double*));printf("Size of double pointer type: %d \n",sizeof(int**));}

    Output

    Run the code and check its output −

    Size of int data type: 8
    Size of char data type: 8
    Size of float data type: 8
    Size of double data type: 8
    Size of double pointer type: 8
    
  • Ternary Operator

    The ternary operator (?:) in C is a type of conditional operator. The term “ternary” implies that the operator has three operands. The ternary operator is often used to put multiple conditional (if-else) statements in a more compact manner.

    Syntax of Ternary Operator in C

    The ternary operator is used with the following syntax −

    exp1 ? exp2 : exp3
    

    It uses three operands −

    • exp1 − A Boolean expression evaluating to true or false
    • exp2 − Returned by the ? operator when exp1 is true
    • exp3 − Returned by the ? operator when exp1 is false

    Example 1: Ternary Operator in C

    The following C program uses the ternary operator to check if the value of a variable is even or odd.

    #include <stdio.h>intmain(){int a =10;(a %2==0)?printf("%d is Even \n", a):printf("%d is Odd \n", a);return0;}

    Output

    When you run this code, it will produce the following output −

    10 is Even
    

    Change the value of “a” to 15 and run the code again. Now you will get the following output −

    15 is Odd
    

    Example 2

    The conditional operator is a compact representation of ifelse construct. We can rewrite the logic of checking the odd/even number by the following code −

    #include <stdio.h>intmain(){int a =10;if(a %2==0){printf("%d is Even\n", a);}else{printf("%d is Odd\n", a);}return0;}

    Output

    Run the code and check its output −

    10 is Even
    

    Example 3

    The following program compares the two variables “a” and “b”, and assigns the one with the greater value to the variable “c”.

    #include <stdio.h>intmain(){int a =100, b =20, c;
    
       c =(a >= b)? a : b;printf("a: %d b: %d c: %d\n", a, b, c);return0;}

    Output

    When you run this code, it will produce the following output −

    a: 100 b: 20 c: 100
    

    Example 4

    The corresponding code with ifelse construct is as follows −

    #include <stdio.h>intmain(){int a =100, b =20, c;if(a >= b){
    
      c = a;}else{
      c = b;}printf("a: %d b: %d c: %d\n", a, b, c);return0;}</code></pre>

    Output

    Run the code and check its output −

    a: 100 b: 20 c: 100
    

    Example 5

    If you need to put multiple statements in the true and/or false operand of the ternary operator, you must separate them by commas, as shown below −

    #include <stdio.h>intmain(){int a =100, b =20, c;
    
       c =(a >= b)?printf("a is larger "), c = a :printf("b is larger "), c = b;printf("a: %d b: %d c: %d\n", a, b, c);return0;}

    Output

    In this code, the greater number is assigned to "c", along with printing the appropriate message.

    a is larger a: 100 b: 20 c: 20
    

    Example 6

    The corresponding program with the use of ifelse statements is as follows −

    #include <stdio.h>intmain(){int a =100, b =20, c;if(a >= b){printf("a is larger \n");
    
      c = a;}else{printf("b is larger \n");
      c = b;}printf("a: %d b: %d c: %d\n", a, b, c);return0;}</code></pre>

    Output

    Run the code and check its output −

    a is larger
    a: 100 b: 20 c: 100
    

    Nested Ternary Operator

    Just as we can use nested if-else statements, we can use the ternary operator inside the True operand as well as the False operand.

    exp1 ?(exp2 ? expr3 : expr4):(exp5 ? expr6: expr7)

    First C checks if expr1 is true. If so, it checks expr2. If it is true, the result is expr3; if false, the result is expr4.

    If expr1 turns false, it may check if expr5 is true and return expr6 or expr7.

    Example 1

    Let us develop a C program to determine whether a number is divisible by 2 and 3, or by 2 but not 3, or 3 but not 2, or neither by 2 and 3. We will use nested condition operators for this purpose, as shown in the following code −

    #include <stdio.h>intmain(){int a =15;printf("a: %d\n", a);(a %2==0)?((a%3==0)?printf("divisible by 2 and 3"):printf("divisible by 2 but not 3")):((a%3==0)?printf("divisible by 3 but not 2"):printf("not divisible by 2, not divisible by 3"));return0;}

    Output

    Check for different values −

    a: 15
    divisible by 3 but not 2
    
    a: 16
    divisible by 2 but not 3
    
    a: 17
    not divisible by 2, not divisible by 3
    
    a: 18
    divisible by 2 and 3
    

    Example 2

    In this program, we have used nested ifelse statements for the same purpose instead of conditional operators −

    #include <stdio.h>intmain(){int a =15;printf("a: %d\n", a);if(a %2==0){if(a %3==0){printf("divisible by 2 and 3");}else{printf("divisible by 2 but not 3");}}else{if(a %3==0){printf("divisible by 3 but not 2");}else{printf("not divisible by 2, not divisible by 3");}}return0;}

    Output

    When you run this code, it will produce the following output −

    a: 15
    divisible by 3 but not 2
    
  • Increment and Decrement Operators

    C – Increment and Decrement Operators

    The increment operator (++) increments the value of a variable by 1, while the decrement operator (–) decrements the value.

    Increment and decrement operators are frequently used in the construction of counted loops in C (with the for loop). They also have their application in the traversal of array and pointer arithmetic.

    The ++ and — operators are unary and can be used as a prefix or posfix to a variable.

    Example of Increment and Decrement Operators

    The following example contains multiple statements demonstrating the use of increment and decrement operators with different variations −

    #include <stdio.h>intmain(){int a =5, b =5, c =5, d =5;
      
      a++;// postfix increment++b;// prefix increment
      c--;// postfix decrement--d;// prefix decrementprintf("a = %d\n", a);printf("b = %d\n", b);printf("c = %d\n", c);printf("d = %d\n", d);return0;}

    Output

    When you run this code, it will produce the following output −

    a = 6
    b = 6
    c = 4
    d = 4
    

    Example Explanation

    In other words, “a++” has the same effect as “++a”, as both the expressions increment the value of variable “a” by 1. Similarly, “a–” has the same effect as “–a”.

    The expression “a++;” can be treated as the equivalent of the statement “a = a + 1;”. Here, the expression on the right adds 1 to “a” and the result is assigned back to 1, therby the value of “a” is incremented by 1.

    Similarly, “b–;” is equivalent to “b = b 1;”.

    Types of Increment Operator

    There are two types of increment operators – pre increment and post increment.

    Pre (Prefix) Increment Operator

    In an expression, the pre-increment operator increases the value of a variable by 1 before the use of the value of the variable.

    Syntax

    ++variable_name;

    Example

    In the following example, we are using a pre-increment operator, where the value of “x” will be increased by 1, and then the increased value will be used in the expression.

    #include <stdio.h>intmain(){int x =10;int y =10+++x;printf("x = %d, y = %d\n", x, y);return0;}

    When you run this code, it will produce the following output −

    x = 11, y = 21
    

    Post (Postfix) Increment Operator

    In an expression, the post-increment operator increases the value of a variable by 1 after the use of the value of the variable.

    Syntax

    variable_name++;

    Example

    In the following example, we are using post-increment operator, where the value of “x” will be used in the expression and then it will be increased by 1.

    #include <stdio.h>intmain(){int x =10;int y =10+ x++;printf("x = %d, y = %d\n", x, y);return0;}

    When you run this code, it will produce the following output −

    x = 11, y = 20
    

    Types of Decrement Operator

    There are two types of decrement operators – pre decrement and post decrement.

    Pre (Prefix) decrement Operator

    In an expression, the pre-decrement operator decreases the value of a variable by 1 before the use of the value of the variable.

    Syntax

    --variable_name;

    Example

    In the following example, we are using a pre-decrement operator, where the value of “x” will be decreased by 1, and then the decreased value will be used in the expression.

    #include <stdio.h>intmain(){int x =10;int y =10+--x;printf("x = %d, y = %d\n", x, y);return0;}

    When you run this code, it will produce the following output −

    x = 9, y = 19
    

    Post (Postfix) Decrement Operator

    In an expression, the post-decrement operator decreases the value of a variable by 1 after the use of the value of the variable.

    Syntax

    variable_name--;

    Example

    In the following example, we are using post-decrement operator, where the value of “x” will be used in the expression and then it will be decreased by 1.

    #include <stdio.h>intmain(){int x =10;int y =10+ x--;printf("x = %d, y = %d\n", x, y);return0;}

    When you run this code, it will produce the following output −

    x = 9, y = 20
    

    More Examples of Increment and Decrement Operators

    Example 1

    The following example highlights the use of prefix/postfix increment/decrement −

    #include <stdio.h>intmain(){char a ='a', b ='M';int x =5, y =23;printf("a: %c b: %c\n", a, b);
       
       a++;printf("postfix increment a: %c\n", a);++b;printf("prefix increment b: %c\n", b);printf("x: %d y: %d\n", x, y);
       
       x--;printf("postfix decrement x : %d\n", x);--y;printf("prefix decrement y : %d\n", y);return0;}

    Output

    When you run this code, it will produce the following output −

    a: a b: M
    postfix increment a: b
    prefix increment b: N
    
    x: 5 y: 23
    postfix decrement x: 4
    prefix decrement y: 22
    

    The above example shows that the prefix as well as postfix operators have the same effect on the value of the operand variable. However, when these “++” or “–” operators appear along with the other operators in an expression, they behave differently.

    Example 2

    In the following code, the initial values of “a” and “b” variables are same, but the printf() function displays different values −

    #include <stdio.h>intmain(){int x =5, y =5;printf("x: %d y: %d\n", x,y);printf("postfix increment x: %d\n", x++);printf("prefix increment y: %d\n",++y);return0;}

    Output

    Run the code and check its output −

    x: 5 y: 5
    postfix increment x: 5
    prefix increment y: 6
    

    In the first case, the printf() function prints the value of “x” and then increments its value. In the second case, the increment operator is executed first, the printf() function uses the incremented value for printing.

    Operator Precedence of Increment and Decrement Operators

    There are a number of operators in C. When multiple operators are used in an expression, they are executed as per their order of precedence. Increment and decrement operators behave differently when used along with other operators.

    When an expression consists of increment or decrement operators alongside other operators, the increment and decrement operations are performed first. Postfix increment and decrement operators have higher precedence than prefix increment and decrement operators.

    Read also: Operator Precedence in C

    Example 1

    Take a look at the following example −

    #include <stdio.h>intmain(){int x =5, z;printf("x: %d \n", x);
    
       z = x++;printf("x: %d z: %d\n", x, z);return0;}

    Output

    Run the code and check its output −

    x: 5 
    x: 6 z: 5
    

    Since “x++” increments the value of “x” to 6, you would expect “z” to be 6 as well. However, the result shows “z” as 5. This is because the assignment operator has a higher precedence over postfix increment operator. Hence, the existing value of “x” is assigned to “z”, before incrementing “x”.

    Example 2

    Take a look at another example below −

    #include <stdio.h>intmain(){int x =5, y =5, z;printf("x: %d y: %d\n", x,y);
    
       z =++y;printf("y: %d z: %d\n", y ,z);return0;}

    Output

    When you run this code, it will produce the following output −

    y: 5
    y: 6 z: 6
    

    The result may be confusing, as the value of “y” as well as “z” is now 6. The reason is that the prefix increment operator has a higher precedence than the assignment operator. Hence, “y” is incremented first and then its new value is assigned to “z”.

    The associativity of operators also plays an important part. For increment and decrement operators, the associativity is from left to right. Hence, if there are multiple increment or decrement operators in a single expression, the leftmost operator will be executed first, moving rightward.

    Example 3

    In this example, the assignment expression contains both the prefix as well as postfix operators.

    #include <stdio.h>intmain(){int x =5, y =5, z;
    
       z = x+++++y;printf("x: %d y: %d z: %d\n", x,y,z);return0;}

    Output

    Run the code and check its output −

    x: 6 y:6 z: 11
    

    In this example, the first operation to be done is “y++” (“y” becomes 6). Secondly the “+” operator adds “x” (which is 5) and “y”, the result assigned to “z” as 11, and then “x++” increments “x” to 6.

    Using the Increment Operator in Loop

    In C, the most commonly used syntax of a for loop is as follows −

    for(init_val; final_val; increment){statement(s);}

    Example

    The looping body is executed for all the values of a variable between the initial and the final values, incrementing it after each round.

    #include <stdio.h>intmain(){int x;for(x =1; x <=5; x++){printf("x: %d\n", x);}return0;}

    Output

    When you run this code, it will produce the following output −

    x: 1
    x: 2
    x: 3
    x: 4
    x: 5
    
  • Assignment Operators in C

    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 −

    OperatorDescriptionExample
    =Simple assignment operator. Assigns values from right side operands to left side operandC = 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 initializationint y;// declaration
    y =20;// assignment laterint z = x + y;// assign an expressionint 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 statement10=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>intmain(){int a =10;int b =20;
       
       a += b;printf("a: %d", a);return0;}

    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>intmain(){int a =60;int b =2;
       
       a <<= b;printf("a: %d", a);return0;}

    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>intmain(){int a =21;int c ;
    
       c =  a;printf("Line 1 - =  Operator Example, Value of c = %d\n", c );
    
       c +=  a;printf("Line 2 - += Operator Example, Value of c = %d\n", c );
    
       c -=  a;printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
    
       c *=  a;printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
    
       c /=  a;printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
    
       c  =200;
       c %=  a;printf("Line 6 - %%= Operator Example, Value of c = %d\n", c );
    
       c <<=2;printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
    
       c >>=2;printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
    
       c &=2;printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
    
       c ^=2;printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
    
       c |=2;printf("Line 11 - |= Operator Example, Value of c = %d\n", c );return0;}

    Output

    When you compile and execute the above program, it will produce the following result −

    Line 1 - =  Operator Example, Value of c = 21
    Line 2 - += Operator Example, Value of c = 42
    Line 3 - -= Operator Example, Value of c = 21
    Line 4 - *= Operator Example, Value of c = 441
    Line 5 - /= Operator Example, Value of c = 21
    Line 6 - %= Operator Example, Value of c = 11
    Line 7 - <<= Operator Example, Value of c = 44
    Line 8 - >>= Operator Example, Value of c = 11
    Line 9 - &= Operator Example, Value of c = 2
    Line 10 - ^= Operator Example, Value of c = 0
    Line 11 - |= Operator Example, Value of c = 2
    
  • Bitwise Operators

    Bitwise operators in C allow low-level manipulation of data stored in computers 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.

    OperatorDescriptionExample
    &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 abit ba & b
    000
    010
    100
    111

    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 −

    00111100&00001101---------=00001100

    The binary number 00001100 corresponds to 12 in decimal.

    Bitwise OR (|) Operator

    The bitwise OR (|) operator performs as per the following truth table −

    bit abit ba | b
    000
    011
    101
    111

    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 −

    00111100|00001101---------=00111101

    The binary number 00111101 corresponds to 61 in decimal.

    Bitwise XOR (^) Operator

    The bitwise XOR (^) operator performs as per the following truth table −

    bit abit ba ^ b
    000
    011
    101
    110

    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 −

    00111100^00001101---------=00110001

    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 −

    00111100<<2=11110000

    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 bitwise right-shift of its corresponding bits illustrated below −

    00111100>>2=00001111

    The binary number 00001111 corresponds to 15 in decimal.

    The 1’s Complement (~) Operator

    The 1’s compliment operator (~) in C is a unary operator, needing just one operand. It has the effect of “flipping” the bits, which means 1s are replaced by 0s and vice versa.

    a~a
    01
    10

    Assuming that the int variable “a” has the value 60 (equivalent to 0011 1100 in binary), then the “~a” operation results in -61 in 2s complement form, as per the bitwise right-shift of its corresponding bits illustrated below −

    ~00111100=11000011

    The binary number 1100 0011 corresponds to -61 in decimal.

    Example

    In this example, we have highlighted the operation of all the bitwise operators:

    #include <stdio.h>intmain(){unsignedint a =60;/* 60 = 0011 1100 */unsignedint b =13;/* 13 = 0000 1101 */int c =0;           
    
       c = a & b;/* 12 = 0000 1100 */printf("Line 1 - Value of c is %d\n", c );
    
       c = a | b;/* 61 = 0011 1101 */printf("Line 2 - Value of c is %d\n", c );
    
       c = a ^ b;/* 49 = 0011 0001 */printf("Line 3 - Value of c is %d\n", c );
    
       c =~a;/*-61 = 1100 0011 */printf("Line 4 - Value of c is %d\n", c );
    
       c = a <<2;/* 240 = 1111 0000 */printf("Line 5 - Value of c is %d\n", c );
    
       c = a >>2;/* 15 = 0000 1111 */printf("Line 6 - Value of c is %d\n", c );return0;}

    Output

    When you run this code, it will produce the following output −

    Line 1 - Value of c is 12
    Line 2 - Value of c is 61
    Line 3 - Value of c is 49
    Line 4 - Value of c is -61
    Line 5 - Value of c is 240
    Line 6 - Value of c is 15
    
  • Logical Operators in C

    Logical operators in C evaluate to either True or False. Logical operators are typically used with Boolean operands.

    The logical AND operator (&&) and the logical OR operator (||) are both binary in nature (require two operands). The logical NOT operator (!) is a unary operator.

    Since C treats “0” as False and any non-zero number as True, any operand to a logical operand is converted to a Boolean data.

    Here is a table showing the logical operators in C −

    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.(A && B)
    ||Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.(A || B)
    !Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.!(A)

    The result of a logical operator follows the principle of Boolean algebra. The logical operators follow the following truth tables.

    Logical AND (&&) Operator

    The && operator in C acts as the logical AND operator. It has the following truth table −

    aba&&b
    truetrueTrue
    truefalseFalse
    falsetrueFalse
    falsefalseFalse

    The above truth table shows that the result of && is True only if both the operands are True.

    Logical OR (||) Operator

    C uses the double pipe symbol (||) as the logical OR operator. It has the following truth table −

    aba||b
    truetrueTrue
    truefalseTrue
    falsetruetrue
    falsefalsefalse

    The above truth table shows that the result of || operator is True when either of the operands is True, and False if both operands are false.

    Logical NOT (!) Operator

    The logical NOT ! operator negates the value of a Boolean operand. True becomes False, and False becomes True. Here is its truth table −

    A!a
    TrueFalse
    FalseTrue

    Unlike the other two logical operators && and ||, the logical NOT operator ! is a unary operator.

    Example 1

    The following example shows the usage of logical operators in C −

    #include <stdio.h>intmain(){int a =5;int b =20;if(a && b){printf("Line 1 - Condition is true\n");}if(a || b){printf("Line 2 - Condition is true\n");}/* lets change the value of  a and b */
       a =0;
       b =10;if(a && b){printf("Line 3 - Condition is true\n");}else{printf("Line 3 - Condition is not true\n");}if(!(a && b)){printf("Line 4 - Condition is true\n");}return0;}

    Output

    Run the code and check its output −

    Line 1 - Condition is true
    Line 2 - Condition is true
    Line 3 - Condition is not true
    Line 4 - Condition is true
    

    Example 2

    In C, a char type is a subset of int type. Hence, logical operators can work with char type too.

    #include <stdio.h>intmain(){char a ='a';char b ='\0';// Null characterif(a && b){printf("Line 1 - Condition is true\n");}if(a || b){printf("Line 2 - Condition is true\n");}return0;}

    Output

    Run the code and check its output −

    Line 2 - Condition is true
    

    Logical operators are generally used to build a compound boolean expression. Along with relational operators, logical operators too are used in decision-control and looping statements in C.

    Example 3

    The following example shows a compound Boolean expression in a C program −

    #include <stdio.h>intmain(){int phy =50;int maths =60;if(phy <50|| maths <50){printf("Result:Fail");}else{printf("Result:Pass");}return0;}

    Output

    Result:Pass
    

    Example 4

    The similar logic can also be expressed using the && operator as follows −

    #include <stdio.h>intmain(){int phy =50;int maths =60;if(phy >=50&& maths >=50){printf("Result: Pass");}else{printf("Result: Fail");}return0;}

    Output

    Run the code and check its output −

    Result: Pass
    

    Example 5

    The following C code employs the NOT operator in a while loop −

    #include <stdio.h>intmain(){int i =0;while(!(i >5)){printf("i = %d\n", i);
    
      i++;}return0;}</code></pre>

    Output

    In the above code, the while loop continues to iterate till the expression "!(i > 5)" becomes false, which will be when the value of "i" becomes more than 5.

    i = 0
    i = 1
    i = 2
    i = 3
    i = 4
    i = 5
    

    C has bitwise counterparts of the logical operators such as bitwise AND (&), bitwise OR (|), and binary NOT or complement (~) operator.

  • Relational Operators in C

    Relational operators in C are defined to perform comparison of two values. The familiar angular brackets < and > are the relational operators in addition to a few more as listed in the table below.

    These relational operators are used in Boolean expressions. All the relational operators evaluate to either True or False.

    C doesnt have a Boolean data type. Instead, “0” is interpreted as False and any non-zero value is treated as True.

    Example 1

    Here is a simple example of relational operator in C −

    #include <stdio.h>intmain(){int op1 =5;int op2 =3;printf("op1: %d op2: %d op1 < op2: %d\n", op1, op2, op1 < op2);return0;}

    Output

    Run the code and check its output −

    op1: 5 op2: 3 op1 < op2: 0
    

    Relational operators have an important role to play in decision-control and looping statements in C.

    The following table lists all the relational operators in C −

    OperatorDescriptionExample
    ==Checks if the values of two operands are equal or not. If yes, then the condition becomes true.(A == B)
    !=Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.(A != B)
    >Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true.(A > B)
    <Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true.(A < B)
    >=Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true.(A >= B)
    <=Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true.(A <= B)

    All the relational operators are binary operators. Since they perform comparison, they need two operands on either side.

    We use the = symbol in C as the assignment operator. So, C uses the “==” (double equal) as the equality operator.

    The angular brackets > and < are used as the “greater than” and “less than” operators. When combined with the “=” symbol, they form the “>=” operator for “greater than or equal” and “<=” operator for “less than or equal” comparison.

    Finally, the “=” symbol prefixed with “!” (!=) is used as the inequality operator.

    Example 2

    The following example shows all the relational operators in use.

    #include <stdio.h>intmain(){int a =21;int b =10;int c ;printf("a: %d b: %d\n", a,b);if(a == b){printf("Line 1 - a is equal to b\n");}else{printf("Line 1 - a is not equal to b\n");}if(a < b){printf("Line 2 - a is less than b\n");}else{printf("Line 2 - a is not less than b\n");}if(a > b){printf("Line 3 - a is greater than b\n");}else{printf("Line 3 - a is not greater than b \n\n");}/* Lets change value of a and b */
       a =5;
       b =20;printf("a: %d b: %d\n", a,b);if(a <= b){printf("Line 4 - a is either less than or equal to  b\n");}if(b >= a){printf("Line 5 - b is either greater than  or equal to b\n");}if(a != b){printf("Line 6 - a is not equal to b\n");}else{printf("Line 6 - a is equal to b\n");}return0;}

    Output

    When you run this code, it will produce the following output −

    a: 21 b: 10
    Line 1 - a is not equal to b
    Line 2 - a is not less than b
    Line 3 - a is greater than b
    
    a: 5 b: 20
    Line 4 - a is either less than or equal to  b
    Line 5 - b is either greater than  or equal to b
    Line 6 - a is not equal to b
    

    Example 3

    The == operator needs to be used with care. Remember that “=” is the assignment operator in C. If used by mistake in place of the equality operator, you get an incorrect output as follows −

    #include <stdio.h>intmain(){int a =5;int b =3;if(a = b){printf("a is equal to b");}else{printf("a is not equal to b");}return0;}

    Output

    The value of “b” is assigned to “a” which is non-zero, and hence the if expression returns true.

    a is equal to b
    

    Example 4

    We can have “char” types too as the operand for all the relational operators, as the “char” type is a subset of “int” type. Take a look at this example −

    #include <stdio.h>intmain(){char a ='B';char b ='d';printf("a: %c b: %c\n", a,b);if(a == b){printf("Line 1 - a is equal to b \n");}else{printf("Line 1 - a is not equal to b \n");}if(a < b){printf("Line 2 - a is less than b \n");}else{printf("Line 2 - a is not less than b \n");}if(a > b){printf("Line 3 - a is greater than b \n");}else{printf("Line 3 - a is not greater than b \n");}if(a != b){printf("Line 4 - a is not equal to b \n");}else{printf("Line 4 - a is equal to b \n");}return0;}

    Output

    Run the code and check its output −

    a: B b: d
    Line 1 - a is not equal to b
    Line 2 - a is less than b
    Line 3 - a is not greater than b
    Line 4 - a is not equal to b
    

    Relational operators cannot be used for comparing secondary types such as arrays or derived types such as struct or union types.

  • Unary Operators in C

    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>intmain(){char x ='A';char y =+x;float a =1.55;float b =+a;printf("x: %c y: %c\n", x,y);printf("a: %f y: %f\n", a,b);return0;}

    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>intmain(){int x =5;int y =-x;printf("x: %d y: %d\n", x, y);return0;}

    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>intmain(){char x ='A';printf("Address of x: %d\n",&x);return0;}

    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: %p\n",&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>intmain(){int x =10;int*y =&x;printf("x: %d Address of x: %d\n", x,&x);printf("Value at x with Dereference: %d",*y);return0;}

    Output

    Run the code and check its output −

    x: 10 Address of x: 6422036
    Value at x with Dereference: 10
    

    Example 2

    You can also assign a value to the original variable with the help of the dereference pointer −

    #include <stdio.h>intmain(){int x =10;int*y =&x;printf("x: %d Address of x %d\n", x,&x);*y =20;printf("x: %d with Dereference: %d", x,*y);return0;}

    Output

    Run the code and check its output −

    x: 10 Address of x: 6422036
    x: 20 with dereference: 20
    

    The Logical NOT Operator (!) in C

    The logical NOT operator (!) in C negates the value of a Boolean operand. True becomes False and False becomes True. The logical NOT operator (!) is a unary operator.

    Example 1

    The following example shows the usage of logical operators in C −

    #include <stdio.h>intmain(){int a =0;int b =20;if(!(a && b)){printf("Line 1 - Condition is true\n");}return0;}

    Output

    Line 1 - Condition is true
    

    Example 2

    The following C code employs the NOT operator in a while loop −

    #include <stdio.h>intmain(){int i =0;while(!(i >5)){printf("i = %d\n", i);
    
      i++;}return0;}</code></pre>

    Output

    In this code, the while loop continues to iterate till the expression "!(i > 5)" becomes False, which will be when the value of "i" becomes more than 5.

    i = 0
    i = 1
    i = 2
    i = 3
    i = 4
    i = 5
    

    The 1's Complement Operator (~) in C

    The 1's complement operator (~) in C is a unary operator, needing just one operand. It has the effect of "flipping" the bits, which means the 1's are replaced by 0's and vice versa in the binary representation of any number.

    a~a
    01
    10

    Assuming that the int variable "a" has the value 60 (equivalent to 0011 1100 in binary), the "~a" operation results in -61 in 2s complement form, as per the bitwise right-shift of its corresponding bits.

    ~00111100=11000011

    The binary number "1100 0011" corresponds to -61 in decimal.

    Example

    Take a look at this example code −

    #include <stdio.h>intmain(){int a =60;/* 60 = 0011 1100 */int c =0;
    
       c =~a;/* -61 = 1100 0011 */printf("Value of c is %d \n", c);return0;}

    Output

    When you run this code, it will produce the following output −

    Value of c is -61
    
  • Arithmetic Operators in C

    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 −

    OperatorDescription
    +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>intmain(){int op1 =10;int op2 =3;printf("Operand1: %d Operand2: %d \n\n", op1, op2);printf("Addition of op1 and op2: %d\n", op1 + op2);printf("Subtraction of op2 from op1: %d\n", op1 - op2);printf("Multiplication of op1 and op2: %d\n", op1 * op2);printf("Division of op1 by op2: %d\n", op1/op2);return0;}

    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: %f\n", 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: %f\n",(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>intmain(){int op1 =10;float op2 =2.5;printf("Operand1: %d Operand2: %f\n", op1, op2);printf("Addition of op1 and op2: %f\n", op1 + op2);printf("Subtraction of op2 from op1: %f\n", op1 - op2);printf("Multiplication of op1 and op2: %f\n", op1 * op2);printf("Division of op1 by op2: %f\n", op1/op2);return0;}

    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>intmain(){char op1 ='F';int op2 =3;printf("operand1: %c operand2: %d\n", op1, op2);printf("Addition of op1 and op2: %d\n", op1 + op2);printf("Subtraction of op2 from op1: %d\n", op1 - op2);printf("Multiplication of op1 and op2: %d\n", op1 * op2);printf("Division of op1 by op2: %d\n", op1/op2);return0;}

    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>intmain(){int op1 =10;int op2 =3;printf("Operand1: %d Operand2: %d\n", op1, op2);printf("Modulo of op1 and op2: %d\n", op1%op2);return0;}

    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 the program again −

    float op1 =10;int op2 =3;printf("Modulo of op1 and op2: %d\n", op1%op2);

    Now, you will get a type mismatch error with the following message −

    error: invalid operands to binary % (have 'float' and 'int')
    

    It does allow char operands for modulo operations though.

    Negation Operator in C

    The increment and decrement operators represented by the symbols ++ and  are unary operators. They have been covered in a separate chapter. The “” symbol, representing subtraction operator, also acts a unary negation operator.

    Example

    The following example highlights how you can use the negation operator in C −

    #include <stdio.h>intmain(){int op1 =5;int op2 =-op1;printf("Operand1: %d Operand2: %d\n", op1, op2);return0;}

    Output

    When you run this code, it will produce the following output −

    Operand1: 5 Operand2: -5
    

    In the above example, the “” symbol returns the negative value of op1 and assigns the same to op2.

  • Operators

    An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. By definition, an operator performs a certain operation on operands. An operator needs one or more operands for the operation to be performed.

    Depending on how many operands are required to perform the operation, operands are called as unary, binary or ternary operators. They need one, two or three operands respectively.

    • Unary operators − ++ (increment), — (decrement), ! (NOT), ~ (compliment), & (address of), * (dereference)
    • Binary operators − arithmetic, logical and relational operators except !
    • Ternary operators − The ? operator

    C language is rich in built-in operators and provides the following types of operators −

    • Arithmetic Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Assignment Operators
    • Misc Operators

    We will, in this chapter, look into the way each operator works. Here, you will get an overview of all these chapters. Thereafter, we have provided independent chapters on each of these operators that contain plenty of examples to show how these operators work in C Programming.

    Arithmetic Operators

    We are most familiar with the arithmetic operators. These operators are used to perform arithmetic operations on operands. The most common arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/).

    In addition, the modulo (%) is an important arithmetic operator that computes the remainder of a division operation. Arithmetic operators are used in forming an arithmetic expression. These operators are binary in nature in the sense they need two operands, and they operate on numeric operands, which may be numeric literalsvariables or expressions.

    For example, take a look at this simple expression −

    a + b
    

    Here “+” is an arithmetic operator. We shall learn more about arithmetic operators in C in a subsequent chapter.

    The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then −

    Show Examples

    OperatorDescriptionExample
    &plus;Adds two operands.A &plus; B = 30
    Subtracts second operand from the first.A − B = -10
    *Multiplies both operands.A * B = 200
    /Divides numerator by de-numerator.B / A = 2
    %Modulus Operator and remainder of after an integer division.B % A = 0
    ++Increment operator increases the integer value by one.A++ = 11
    Decrement operator decreases the integer value by one.A– = 9

    Relational Operators

    We are also acquainted with relational operators while learning secondary mathematics. These operators are used to compare two operands and return a boolean value (true or false). They are used in a boolean expression.

    The most common relational operators are less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equal to (==), and not equal to (!=). Relational operators are also binary operators, needing two numeric operands.

    For example, in the Boolean expression −

    a > b
    

    Here, “>” is a relational operator.

    We shall learn more about with relational operators and their usage in one of the following chapters.

    Show Examples

    OperatorDescriptionExample
    ==Checks if the values of two operands are equal or not. If yes, then the condition becomes true.(A == B) is not true.
    !=Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.(A != B) is true.
    >Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true.(A > B) is not true.
    <Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true.(A < B) is true.
    >=Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true.(A >= B) is not true.
    <=Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true.(A <= B) is true.

    Logical Operators

    These operators are used to combine two or more boolean expressions. We can form a compound Boolean expression by combining Boolean expression with these operators. An example of logical operator is as follows −

    a >=50&& b >=50

    The most common logical operators are AND (&&), OR(||), and NOT (!). Logical operators are also binary operators.

    Show Examples

    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.(A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.(A || B) is true.
    !Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.!(A && B) is true.

    We will discuss more about Logical Operators in C in a subsequent chapter.

    Bitwise Operators

    Bitwise operators let you manipulate data stored in computers memory. These operators are used to perform bit-level operations on operands.

    The most common bitwise operators are AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). Here the “~” operator is a unary operator, while most of the other bitwise operators are binary in narure.

    Bitwise operator works on bits and perform bit−by−bit operation. The truth tables for &, “|”, and “^” are as follows −

    pqp & qp | qp ^ q
    00000
    01011
    11110
    10011

    Assume A = 60 and B = 13 in binary format, they will be as follows −

    A = 0011 1100

    B = 0000 1101

    ————————

    A&B = 0000 1100

    A|B = 0011 1101

    A^B = 0011 0001

    ~A = 1100 0011

    The following table lists the bitwise operators supported by C. Assume variable ‘A’ holds 60 and variable ‘B’ holds 13, then −

    Show Examples

    OperatorDescriptionExample
    &Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) = 12, i.e., 0000 1100
    |Binary OR Operator copies a bit if it exists in either operand.(A | B) = 61, i.e., 0011 1101
    ^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) = 49, i.e., 0011 0001
    ~Binary One’s Complement Operator is unary and has the effect of ‘flipping’ bits.(~A ) = ~(60), i.e,. -0111101
    <<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 = 240 i.e., 1111 0000
    >>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 = 15 i.e., 0000 1111

    Assignment Operators

    As the name suggests, an assignment operator “assigns” or sets a value to a named variable in C. These operators are used to assign values to variables. The “=” symbol is defined as assignment operator in C, however it is not to be confused with its usage in mathematics.

    The following table lists the assignment operators supported by the C language −

    Show Examples

    OperatorDescriptionExample
    =Simple assignment operator. Assigns values from right side operands to left side operandC = 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

    Hence, the expression “a = 5” assigns 5 to the variable “a”, but “5 = a” is an invalid expression in C.

    The “=” operator, combined with the other arithmetic, relational and bitwise operators form augmented assignment operators. For example, the += operator is used as add and assign operator. The most common assignment operators are =, +=, -=, *=, /=, %=, &=, |=, and ^=.

    Misc Operators &map; sizeof & ternary

    Besides the operators discussed above, there are a few other important operators including sizeof and ? : supported by the C Language.

    Show Examples

    OperatorDescriptionExample
    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 : otherwise value Y

    Operators Precedence in C

    Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.

    For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

    Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    Show Examples

    CategoryOperatorAssociativity
    Postfix() [] -> . ++ – –Left to right
    Unary+ – ! ~ ++ – – (type)* & sizeofRight to left
    Multiplicative* / %Left to right
    Additive+ –Left to right
    Shift<< >>Left to right
    Relational< <= > >=Left to right
    Equality== !=Left to right
    Bitwise AND&Left to right
    Bitwise XOR^Left to right
    Bitwise OR|Left to right
    Logical AND&&Left to right
    Logical OR||Left to right
    Conditional?:Right to left
    Assignment= += -= *= /= %=>>= <<= &= ^= |=Right to left
    Comma,Left to right

    Other Operators in C

    Apart from the above, there are a few other operators in C that are not classified into any of the above categories. For example, the increment and decrement operators (++ and –) are unary in nature and can appear as a prefix or postfix to the operand.

    The operators that work with the address of memory location such as the address-of operator (&) and the dereference operator (*). The sizeof operator (sizeof) appears to be a keyword but really an operator.

    C also has the type cast operator (()) that forces the type of an operand to be changed. C also uses the dot (.) and the arrow (->) symbols as operators when dealing with derived data types such as struct and union.

    The C99 version of C introduced a few additional operators such as auto, decltype.

    A single expression in C may have multiple operators of different type. The C compiler evaluates its value based on the operator precedence and associativity of operators. For example, in the following expression −

    a + b * c
    

    The multiplication operand takes precedence over the addition operator.

    We shall understand these properties with examples in a subsequent chapter.

    Many other programming languages, which are called C-family languages (such as C++, C#, Java, Perl and PHP) have an operator nomenclature that is similar to C.