Saturday 30 December 2017

Bitwise Operators in C and C++ Programming Languages


Uses of Bitwise Operators and Why to Study Bitwise.

  1. Compression: Occasionally, you may want to implement a large number of Boolean variables, without using a lot of space. A 32-bit int can be used to store 32 Boolean variables. Normally, the minimum size for one Boolean variable is one byte. All types in C must have sizes that are multiples of bytes. However, only one bit is necessary to represent a Boolean value.
  2. Set operations: You can also use bits to represent elements of a (small) set. If a bit is 1, then element i is in the set, otherwise it's not. You can use bitwise AND to implement set intersection, bitwise OR to implement set union.
  3. Encryption: swapping the bits of a string for e.g. according to a predefined shared key will create an encrypted string.
& (bitwise AND): Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
 
| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
 
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.

 << (left shift) Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

>> (right shift) Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.

~ (bitwise NOT) Takes one number and inverts all bits of it

Following is example C program.


 

Following are interesting facts about bitwise operators.

  • The left shift and right shift operators should not be used for negative numbers The result of is undefined behabiour if any of the operands is a negative number. For example results of both -1 << 1 and 1 << -1 is undefined. Also, if the number is shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. 
  •  The bitwise XOR operator is the most useful operator from technical interview perspective. It is used in many problems. A simple example could be “Given a set of numbers where all elements occur even number of times except one number, find the odd occurring number” This problem can be efficiently solved by just doing XOR of all numbers. For examples click here.
  •  The bitwise operators should not be used in place of logical operators. The result of logical operators (&&, || and !) is either 0 or 1, but bitwise operators return an integer value. Also, the logical operators consider any non-zero operand as 1. For example, consider the following program, the results of & and && are different for same operands. 
int main() 

 int x = 2, y = 5;
 (x & y)? printf("True ") : printf("False ");
 (x && y)? printf("True ") : printf("False ");
 return 0; 

Output: 
False True

    • The left-shift and right-shift operators are equivalent to multiplication and division by 2 respectively. As mentioned in point 1, it works only if numbers are positive. 
    int main() 
    { int x = 19; 
     printf ("x << 1 = %d\n", x << 1); 
    printf ("x >> 1 = %d\n", x >> 1);
    return 0;
    }

    Output:
    38 9

    • The & operator can be used to quickly check if a number is odd or even. The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value would be zero.
    int main()
    {
    int x = 19;
    (x & 1)? printf("Odd"): printf("Even");
    return 0;
    }

    Output: Odd

    • <1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b="">The ~ operator should be used carefully<1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b="">. The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And result may be negative number if result is stored in signed variable (assuming that the negative numbers are stored in 2’s complement form where leftmost bit is the sign bit)
      <1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b="">
    <1 00001000="" b="" d="" is="" n="" printf="" result="" the=""><1 16="" b=""> // Note that the output compiler dependent
    int main()
    {
    unsigned int x = 1;
    printf("SIgned %d \n", ~x);
    printf("Unsigned %ud \n", ~x);
    return 0;
    }


    Output:
    Signed Result -2
    Unsigned Result 24967294d */


    Interesting facts about Operator Precedence and Associativity in C Language

    Operator precedence decides which operator’s operation should be performed first in an expression with more than one operators with different precedence.

    For example 8+ 2 * 10 is calculated as 8 + (2 * 10) and not as (8 + 2) * 10.

    Associativity in C is used when two operators of same precedence present in an expression. Associativity can be either Left to Right or Right to Left.

    For example ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

    Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub expressions in absence of brackets.
    • Associativity is used only when there are two or more operators of same precedence. Associativity doesn’t define the order in which operands of a single operator are evaluated. 
           For example associativity of the * operator is high so 2*3 performed first that 6+1 that is 7 assigned to a.          int a = 1+2*3;
    • All operators with same precedence have same associativity. This is necessary, otherwise there won’t be any way for compiler to decide evaluation order of expressions which have two operators of same precedence and different associativity. 
          For example + and – have same associativity.
    • Precedence and associativity of postfix ++ and prefix ++ are different
    • Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left. 
    Click here for more on Pre/post increments.
    • Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1.
    #include
    int main()
    {
    int a;
    a = 1, 2, 3; // Evaluated as (a = 1), 2, 3
    printf("%d", a);
    return 0;
    }


     Output:
    1

    Sunday 24 December 2017

    Operators in C and C++

    Operators are the foundation of any programming language. Thus the functionality of C language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C, operators in Can be categorized in following categories:

    • Arithmetic Operators (+, -, *, /, %, post-increment, pre-increment, post-decrement, pre-decrement)
    • Relational Operators (==, != , >, <, >= & <=) Logical Operators (&&, || and !) 
    •  Bitwise Operators (&, |, ^, ~, >> and <<) • Assignment Operators (=, +=, -=, *=, etc) 
    • Other Operators (conditional, comma, sizeof, address, redirecton) 

    Arithmetic Operators: These are used to perform arithmetic/mathematical operations on operands.

    The binary operators falling in this category are:

    • Addition: The ‘+’ operator adds two operands. For example, x+y. 
    • Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y. 
    • Multiplication: The ‘*’ operator multiplies two operands. For example, x*y. 
    • Division: The ‘/’ operator divides the first operand by the second. For example, x/y. 
    • Modulus: The ‘%’ operator returns the remainder when first operand is divided by the second. For example, x%y. 
     The ones falling into the category of unary arithmetic operators are:

    Increment: The ‘++’ operator is used to increment the value of an integer. When placed before the variable name (also called pre-increment operator), its value is incremented instantly. For example, ++x. And when it is placed after the variable name (also called post-increment operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x++.

    Decrement: The ‘–‘ operator is used to decrement the value of an integer. When placed before the variable name (also called pre-decrement operator), its value is decremented instantly. For example, –x. And when it is placed after the variable name (also called post-decrement operator), its value is preserved temporarily until the execution of this statement and it gets updated before the execution of the next statement. For example, x–.

    Relational Operators: 

    Relational operators are used for comparison of two values. Let’s see them one by one:

    •  ‘==’ operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise it returns false. For example, 1==1 will return true. 
    • ‘!=’ operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 1!=1 will return false. 
    • ‘>’ operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 8>5 will return true.
    • ‘<‘ operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise it returns false. For example, 8<5 operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false.
    • ‘>=’ operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return true.
    • ‘<=’ operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also return true.


    Logical Operators:

    They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:

    Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).

    Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.

    Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.

    Short-Circuiting in Logical Operators:


    In case of logical AND, the second operand is not evaluated if first operand is false. For example,  below doesn’t print “Geeks4Coding” as the first operand of logical AND itself is false.

    bool res = ((a == b) && printf("Geeks4Coding"));

    In case of logical OR, the second operand is not evaluated if first operand is true. For example,  below doesn’t print “Geeks4Coding” as the first operand of logical OR itself is true.

    int a=10, b=4;
    bool res = ((a != b) || printf("Geeks4Coding"));

    Constant in C/C++

    Constant is a variables or values in C programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc.

    Every constant has some range. The integers that is too big to fit into an int will be taken as a long. Now there are various ranges that differ from unsigned to signed bits. Under signed bit the range of an int, varies from -128 to +127 and under unsigned bit int varies from 0 to 255.

    Defining Constants

    In C program we can define constants in two ways as shown below:
    • Using #define preprocessor directive
    • Using a const keyword.
    Let us now learn about above two ways in details:

    Using #define preprocessor directive : This directive used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:

    #define VarName value

    where Varname is the name given to constant and value is any value assigned to it.

    Below is the C program to explain how to use #define to declare constants:

    #include<stdio.h>
    #define val 10
    #define floatVal 4.5
    #define charVal 'G'

    int main()
    {
    printf("Integer Constant: %d\n",val);
    printf("Floating point Constant: %f\n",floatVal);
    printf("Character Constant: %c\n",charVal);

    return 0;
    }

     

    Output:
     

    Integer Constant: 10
    Floating point Constant: 4.500000
    Character Constant: G

     

    Read Macros and Preprocessors directives in C.

     Using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword. Below program shows how to use const to declare costants of different data types:

    #include<stdio.h>
    int main()
    {
    const int intVal = 10; // int constant
    const float floatVal = 4.14; // Real constant
    const char charVal = 'A'; // char constant
    const char stringVal[10] = "ABC"; // string constant

    printf("Integer constant :%d \n", intVal );
    printf("Floating point constant : %f \n", floatVal );
    printf("Character constant : %c \n", charVal );
    printf("String constant : %s \n", stringVal);

    return 0;
    }

     

    Output:
     

    Integer constant :10
    Floating point constant : 4.140000
    Character constant : A
    String constant : ABC

     

    Learn about Const Qualifier in C.
     

    String Literals : When string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read only block (generally in data segment) that is shared among functions.
     

    char *str = "GfG";
     

    In the above line “GfG” is stored in a read only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at present str. So this kind of string should only be used when we don’t want to modify string at a later stage in program.
     

    The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory.
     

    int main()
    {
    char *str;

    /* Stored in read only part of data segment */
    str = "GfG";

    /* Problem: trying to modify read only memory */
    *(str+1) = 'n';
    return 0;
    }


    Extern keyword in C / C++

    Keyword extern is used for declaring extern variables in c. This modifier is used with all data types like int, float, double, array, pointer, structure, function etc.

    Facts about extern keyword:

    1. It is default storage class of all global variables as well all functions.

    For example, Analyze following second.c code and its output:

    (a)

    #include <stdio.h>

    int a; //By default it is extern variable

    int main(){

    printf("%d",a);

    return 0;

    }


    Output: 0

    (b)

    #include <stdio.h>

    extern int a;//extern variable

    int main(){

    printf("%d",a);

    return 0;

    }


    Output: Compilation error, undefined symbol i.

    In Both program variable a is extern variable. Read second and third points for explaination.

    (c)
    #include <stdio.h>

    void add(int,int) //extern by default.

    int main(){

    int x=15,y=10;

    add(x,y);

    return 0;

    }


    void sum(int x,int y){

    printf("%d”",x+y);

    }

    Output: 25

    1. When we use extern with any variables it is only declaration that is memory is not allocated for that variable. Hence in second case compiler is showing error unknown symbol a. To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables. For example:

    #include <stdio.h>

    extern int a=1000; //extern variable

    int main(){

    printf("%d",a);

    return 0;

    }


    Output: 1000

    3. If you will not use extern keyword with global variables then compiler will automatically initialize with default value to extern variable.

    4. Default initial value of extern integral type variable is zero otherwise null. For example:

    #include <stdio.h>

    char c;

    int i;

    float f;

    char *str;

    int main(){

    printf("%d %d %f %s",c,i,f,str);

    return 0;

    }


    Output: 0 0 0.000000 (null)

    5. We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally. For example:

    (a)

    #include <stdio.h>

    int main(){

    extern int i=10; //Try to initialize extern variable

    //locally.

    printf("%d",i);

    return 0;

    }

    Output: Compilation error: Cannot initialize extern variable.

    (b)

    #include <stdio.h>

    int main(){

    extern int i; //Declaration of extern variable i.

    int i=10; //Try to locally initialization of

    //extern variable i.

    printf("%d",i);

    return 0;

    }


    Output: Compilation error: Multiple declaration of variable i.

    6. If we declare any variable as extern variable then it searches that variable either it has been initialized or not. If it has been initialized which may be either extern or static* then it is ok otherwise compiler will show an error. For example:

    (a)

    #include <stdio.h>

    int main(){

    extern int i; //It will search the initialization of

    //variable i.

    printf("%d",i);

    return 0;

    }

    int i=20; //Initialization of variable i.
    Output: 20

    (b)

    #include <stdio.h>

    int main(){

    extern int i; //It will search the any initialized

    //variable i which may be static or

    //extern.

    printf("%d",i);

    return 0;

    }

    extern int i=20; //Initialization of extern variable i.


    Output: 20

    (c)

    #include <stdio.h>

    int main(){

    extern int i; //It will search the any initialized

    //variable i which may be static or

    //extern.

    printf("%d",i);

    return 0;

    }

    static int i=20; //Initialization of static variable i.

    Output: 20

    (d)

    #include <stdio.h>

    int main(){

    extern int i; //variable i has declared but not

    //initialized

    printf("%d",i);

    return 0;

    }


    Output: Compilation error: Unknown symbol i.


    7. A particular extern variable can be declared many times but we can initialize at only one time. For example:

    (a)

    extern int i; //Declaring the variable i.

    int i=25; //Initializing the variable.

    extern int i; //Again declaring the variable i.

    #include


    int main(){

    extern int i; //Again declaring the variable i.

    printf("%d",i);

    return 0;

    }


    Output: 25


    (b)

    extern int i; //Declaring the variable

    int i=25; //Initializing the variable

    #include


    int main(){

    printf("%d",i);

    return 0;

    }

    int i=20; //Initializing the variable

    Output: Compilation error: Multiple initialization variable i.

    8. We cannot write any assignment statement globally. For example:

    #include <stdio.h>

    extern int i;

    int i=10; //Initialization statement

    i=25; //Assignment statement

    int main(){

    printf("%d",i);

    return 0;

    }

    Output: Compilation error

    Note: Assigning any value to the variable at the time of declaration is known as initialization while assigning any value to variable not at the time of declaration is known assignment.

    (b)

    #include <stdio.h>

    extern int i;

    int main(){

    i=25; //Assignment statement

    printf("%d",i);

    return 0;

    }


    int i=10; //Initialization statement

    Output: 25

    9. If declared an extern variables or function globally then its visibility will whole the program which may contain one file or many files. For example consider a c program which has written in two files named as first.c and second.c:

    (a)
    //first.c
    #include


    int i=25; //By default extern variable

    int j=5; //By default extern variable

    /**

    Above two line is initialization of variable i and j.

    */

    void main(){

    clrscr();

    sum();

    getch();

    }




    //second.c

    #include


    extern int i; //Declaration of variable i.

    extern int j; //Declaration of variable j.

    void sum(){

    int s;

    s=i+j;

    printf("%d",s);

    }


    Compile and execute above two file first.c and second.c at the same time:



    Storage Classes in C

    A storage class defines the scope or visibility and life-time of variables and or a functions within a C Program. They prefix data type . There four different storage classes in a C program −
    • auto
    • register
    • static
    • extern

    Auto Storage Class

    The auto storage class is the default storage class for all local variables. And use of it does not change anything for normal local variable.

    int main()
    {
    int mount;
    auto int month;
    }

    The above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables.

    Register Storage Class

     The register storage class is used to store local variables on register instead of RAM. This means that the variable has a maximum size equal to the register size and can't use unary '&' operator to get its memory location.

    {
    register int miles;
    }

    The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.

    Static Storage Class

    Static variables have a property of preserving their value even after they are out of their scope. Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

    Syntax:
    static data_type var_name = var_value;

    Following are some interesting facts about static variables in C.

    •   A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.
    For example, we can use static int to count number of times a function is called, but an auto variable can’t be sued for this purpose.

    For example below program prints “1 2”

    #include<stdio.h>
    int fun()
    {
    static int count = 0;
    count++;
    return count;
    }

    int main()
    {
    printf("%d ", fun());
    printf("%d ", fun());
    return 0;
    }

     

    Output:
     

    1 2
    But below program prints 1 1

     

    #include<stdio.h>
    int fun()
    {
    int count = 0;
    count++;
    return count;
    }

    int main()
    {
    printf("%d ", fun());
    printf("%d ", fun());
    return 0;
    }

     

    Output:
     

    1 1

    • Static variables are allocated memory in data segment, not stack segment.
    • Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.

    #include <stdio.h>

     int main()
    {
    static int x;
    int y;
    printf("%d \n %d", x, y);
    }

     

    Output:
     

    0
    [some_garbage_value]


    • In C, static variables can only be initialized using constant literals. For example, following program fails in compilation.
      #include <stdio.h>
    int initializer(void)
    {
    return 50;
    }

    int main()
    {
    static int i = initializer();
    printf(" value of i = %d", i);
    getchar();
    return 0;
    }

     

    Output
     

    In function 'main':
    error: initializer element is not constant
    static int i = initializer();
    ^

    Please note that this condition doesn’t hold in C++. So if you save the program as a C++ program, it would compile \and run fine.

    • Static global variables and functions are also possible in C/C++. The purpose of these is to limit scope of a variable or function to a file. Please refer Static functions in C for more details.

    Extern Storage Class

    The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.
     

    When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.
     

    Please refer Extern keyword for more details

    Saturday 23 December 2017

    Data Types and Modifiers in C/C++

    Data Types

    They are used to define type of variables and contents used. Data types define the way you use storage in the programs you write. Data types can be built in or abstract.

    Built in Data Types: These are the data types which are predefined and are wired directly into the compiler. eg: int, char etc.

    User defined or Abstract data types: These are the type, that user creates as a class. In C++ these are classes where as in C it was implemented by structures. 

    Modifiers

    Specifiers modify the meanings of the predefined built-in data types and expand them to a much larger set. There are four data type modifiers in C++, they are :

    • long
    • short
    • signed
    • unsigned

    Below mentioned are some important points you must know about the modifiers,

    • long and short modify the maximum and minimum values that a data type will hold.
    • A plain int must have a minimum size of short.
    • Size hierarchy : short int < int < long int 
    • Size hierarchy for floating point numbers is : float < double < long double 
    • long float is not a legal type and there are no short floating point numbers. 
    • Signed types includes both positive and negative numbers and is the default type. 
    • Unsigned, numbers are always without any sign, that is always positive. 

    Here are some logical and interesting facts about data-types and the modifiers associated with data-types:-

    1. If no data type is given to a variable, then the compiler automatically converted it to int data type.

    #include <stdio.h>
    int main()
    {
    signed x;
    signed y;

    // size of x and y is equal to the size of int
    printf("The size of x is %d\n", sizeof(x));
    printf("The size of y is %d", sizeof(y));
    return (0);
    }

     

    Output:
     

    The size of x is 4
    The size of y is 4

     

    2. Signed is the default modifier for char and int data types.
     

    #include <stdio.h>
    int main()
    {
    int x;
    char y;
    x = -1;
    y = -2;
    printf("x is %d and y is %d", x, y);
    }

     

    Output:
     

    x is -1 and y is -2.
     

    3. We can’t use any modifiers in float data type. If programmer try to use it then compiler automatically give compile time error.
     

    #include <stdio.h>
    int main()
    {
    signed float a;
    short float b;
    return (0);
    }

     

    Output:
     

    [Error] both 'signed' and 'float' in declaration specifiers
    [Error] both 'short' and 'float' in declaration specifiers

     

    4. Only the long modifier is allowed in double data types. we cant use any other specifier with double data type. If we try any other specifier then compiler will give compile time error.
     

    #include <stdio.h>
    int main()
    {
    long double a;
    return (0);
    }


    #include<stdio.h>

    int main()
    {
    short double a;
    signed double b;
    return (0);
    }

     

    Output:
     

    [Error] both 'short' and 'double' in declaration specifiers
    [Error] both 'signed' and 'double' in declaration specifiers



    Type casting in C

     A type cast is basically a conversion from one type to another. There are two types of type conversion:

    Implicit Type Conversion Also known as ‘automatic type conversion’ and also called as “Widening”.
    • Done by the compiler on its own, without any external trigger from the user.
    • Generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid lose of data.
    • All the data types of the variables are upgraded to the data type of the variable with largest data type. 

             unsigned int -> long -> unsigned -> 

             bool -> char -> short int -> int ->

             long long -> float -> double -> long double

    • It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long long is implicitly converted to float).

    Example of Type Implicit Conversion:


    #include<stdio.h>
    int main()
    {
    int x = 10; // integer x
    char a = 'a'; // character c

    // a implicitly converted to int. ASCII
    // value of 'a' char is 97
    x = x + a;

    // x is implicitly converted to float
    float b = x + 1.0;

    printf("x = %d, z = %f", x, z);
    return 0;
    }

     

    Output:
     

    x = 107, b = 108.000000
     

    Explicit Type Conversion– This process is also called type casting also called as “Narrowing” and it is user defined. Here the user can type cast the result to make it of a particular data type.
     

    The syntax in C:

                (data type) expression

    Type indicated the data type to which the final result is converted.
     

    #include<stdio.h>

    int main()
    {
    double b = 1.2;

    // Explicit conversion from double to int
    int add = (int)b + 1;

    printf("add = %d", add);

    return 0;
    }

     

    Output:
     

    add = 2
     

    Advantages of Type Conversion

    • This is done to take advantage of certain features of type hierarchies or type representations.
       
    • It helps us to compute expressions containing variables of different data types.

    Geeks4Coding

    Contributors

    Popular Posts