Showing posts with label C Language. Show all posts
Showing posts with label C Language. Show all posts

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"));

    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.

    Variables in C


    A variable in simple terms is a storage place which has some memory allocated to it. So basically a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations which can be applied on them.

    Variable Declaration:


    A typical variable declaration is of the form:

    data type variable_name;

    for multiple variables declaration
    data type vr1_name, var2_name, var3_name;

    A variable name can consist of alphabets (both upper and lower case), numbers and the underscore ‘_’ character. However, the name must not start with a number.

    Variable declaration and definition

    Variable declaration refers to the part where a variable is first declared or introduced before its first use. Variable definition is the part where the variable is assigned a memory location and a value. Most of the times, variable declaration and definition are done together.

    #include <stdio.h>
    //extern int c;
    int main()
    {
    char a = 'a'; // declaration and definition of variable 'a123'

    float b;// This is also both declaration &definition/assigned garbage value.

    printf("%c \n", a,c);

    return 0;
    }

     

    Keyword extern is explained here.

    Lvalues and Rvalues in C


    There are two kinds of expressions in C:
     

    Lvalue 

    Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.
     

    Rvalue 

    The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.
     

    Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −
     

    int g = 20; // valid statement

    10 = 20; // invalid statement; would generate compile-time error


    Data Types in C


    All the variable in C has data type associated with it. Each variable require memory which depends on its data type and has some specific operations which can be performed over it. Let us briefly describe them one by one:

    Following are the examples of some very common data types used in C:

    char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.

    int: As the name suggests, an int variable is used to store an integer.

    float: It is used to store decimal numbers (numbers with floating point value) with single precision.

    double: It is used to store decimal numbers (numbers with floating point value) with double precision.

    Void: The type specifier void indicates that no value is available. This data type will be discussed in pointers section. Click here

    Different data types also have different ranges upto which they can store numbers. These ranges may vary from compiler to compiler. Below is list of ranges along with the memory requirement and format specifiers on 32 bit gcc compiler.

    We can use the sizeof() operator to check the size of a variable. See the following C program for the usage of the various data types:

    #include <stdio.h>
    int main()
    {
    int a = 1;
    char b ='G';
    double c = 3.14;
    printf("Hello World!\n");
     

    printf("%c and %lu byte.\n", b,sizeof(char));

    printf("%d and %lu bytes.\n", a,sizeof(int));

    printf("%lf and %lu bytes.\n",c,sizeof(double));

    return 0;
    }


    Output:

    Hello World!

    G and 1 byte.
    1 and 4 bytes.
    3.140000 and 8 bytes.

    Types of Tokens

    A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as follows:
    1.  Keywords
    2. Identifiers
    3. Constants
    4. Strings
    5. Special Symbols
    6. Operators

    Keyword:

     Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords. However, you can specify text to be substituted for keywords before compilation by using C/C++ preprocessor directives.C language supports 32 keywords which are given below:

    auto             break         case            char            const            continue
    default         do             double          else            enum            extern
    float             for             goto              if               int                  long
    register       return         short             signed        sizeof            static
    struct           switch       typedef        union         unsigned        void
    volatile        while

    31 additional keywords other than C in C++ Keywords they are:


    asm                bool                catch                 class
    const_cast    delete            dynamic_cast   explicit
    export            false               friend                 inline
    mutable        namespace new                      operator
    private           protected     public                 reinterpret_cast
    static_cast    template       this                      throw
    true                try                   typeid                typename
    using             virtual            wchar_t


    Identifiers: 

    Identifiers are used as the general terminology for naming of variables, functions and arrays. These are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Once declared, you can use the identifier in later program statements to refer to the associated value. A special kind of identifier, called a statement label, can be used in goto statements.

    There are certain rules that should be followed while naming c identifiers:
    • They must begin with a letter or underscore(_).
    • They must consist of only letters, digits, or underscore. No other special character is allowed.
    • It should not be a keyword.
    • It must not contain white space.
    • It should be up to 31 characters long as only first 31 characters are significant.
    Some examples of c identifiers:

     C program:

    int main()
    {
    int a = 10;
    }

    In the above program there are 2 identifiers:

    main: method name.
    a: variable name.

    Constants

    Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined. Constants refer to fixed values. They are also called as literals.
    Constants may belong to any of the data type.Syntax:

    const

    data_type variable_name; (or) const data_type *variable_name;

    Types of Constants:

    Integer constants – Example: 0, 1, 1218, 12482
    Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
    Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10
    Character constants -Example: ‘a’, ‘A’, ‘z’
    String constants -Example: “GeeksforGeeks”

    Special Symbols: The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #

    Brackets []: Opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts.

    Parentheses (): These special symbols are used to indicate function calls and function parameters.

    Braces {}: These opening and ending curly braces marks the start and end of a block of code containing more than one executable statement.

    Comma (,): It is used to separate more than one statements like in for loop is separates initialization, condition and increment.

    Semi colon: It is an operator that essentially invokes something called an initialization list.

    Asterisk (*): It is used to create pointer variable.

    Assignment operator: It is used to assign values.

    Preprocessor (#): The preprocessor is a macro processor that is used automatically by the compiler to transform your program before actual compilation.

    Operators: Operators are symbols that triggers an action when applied to C variables and other objects. The data items on which operators act upon are called operands. Depending on the number of operands that an operator can act upon, operators can be classified as follows:

    Unary Operators: Those operators that require only single operand to act upon are known as unary operators.For Example increment and decrement operators

    Binary Operators: Those operators that require two operands to act upon are called binary operators.

    Binary operators are classified into :
    • Arithmetic operators
    • Relational Operators
    • Logical Operators
    • Assignment Operators
    • Conditional Operators
    •  Bitwise Operators

     

    Ternary Operators:

     These operators requires three operands to act upon. For Example Conditional operator (?:).

    A ternary operator has the following form,
    exp1 ? exp2 : exp3

    The expression exp1 will be evaluated always. Execution of exp2 and exp3 depends on the outcome of exp1. If the outcome of exp1 is non zero exp2 will be evaluated, otherwise exp3 will be evaluated.



    Basic Syntax of C Program

    A C program basically consists of the following parts −
    • Preprocessor Commands
    • Functions
    • Variables
    • Keywords
    • Statements & Expressions
    • Comments
    Let us take a look at the various parts of the above program

    #include <stdio.h>

    int main() {
    /* multline comment */
    printf("Hello, World! \n");//single line comment

    return 0;
    }
     

    Preprocessor Commands

    #include is a preprocessor command, which tells a C compiler to include stdio.h file from standard library and there won’t be any line with # symbol in object file after compilation, it will get replace by content of stdio.h header file. Learn more about Preprocessor directives. 
     

    Functions

    Main() is the function which tell compiler where to start and there should be only one main() function and printf(),scanf() function are used to print on screen and take input from user.  

    Learn more about Functions

    Variables

    A variable in simple terms is a storage place which has some memory allocated to it. So basically a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations which can be applied on them.

    Keywords

    Keywords are specific reserved words in C each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the C language are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one!
     

    There are a total of 32 keywords in C:  
    auto             break         case            char            const            continue
    default         do              double          else            enum            extern
    float             for             goto              if               int                  long
    register       return        short             signed        sizeof            static
    struct           switch       typedef        union         unsigned        void
    volatile       while
     
    Learn More about Keywords and Variables 
     

    Expressions and Statements

    An expression represents a single data item--usually a number. The expression may consist of a single entity, such as a constant or variable, or it may consist of some combination of such entities, interconnected by one or more operators. Expressions can also represent logical conditions which are either true or false. However, in C, the conditions true and false are represented by the integer values 1 and 0, respectively

    A statement causes the computer to carry out some definite action. There are three different classes of statements in C: expression statements, compound statements, and control statements.
    An expression statement consists of an expression followed by a semicolon. The execution of such a statement causes the associated expression to be evaluated. For example:
     

    a = 6;
    c = a + b;
    ++j;

     

    The first two expression statements both cause the value of the expression on the right of the equal sign to be assigned to the variable on the left. The third expression statement causes the value of j to be incremented by 1. Again, there is no restriction on the length of an expression statement: such a statement can even be split over many lines, so long as its end is signaled by a semicolon.
     

    A compound statement consists of several individual statements enclosed within a pair of braces { }. The individual statements may themselves be expression statements, compound statements, or control statements. Unlike expression statements, compound statements do not end with semicolons. A typical compound statement is shown below:
     

    {
    pi = 3.141593;
    circumference = 2. * pi * radius;
    area = pi * radius * radius;
    }

     

    This particular compound statement consists of three expression statements, but acts like a single entity in the program in which it appears.

    Comments

    Comments are non-executable code used to provide documentation to programmer. Single Line Comment is used to comment out just Single Line in the Code. It is used to provide One Liner Description of line.

     Compiling And Linking    



     C systems generally consist of several parts: a program development environment, the language and the C Standard Library. C programs typically go through six phases to be executed. These are: edit, preprocess, compile, link, load and execute.
     


    Creating a Program


    Edit a file. This is accomplished with an editor program. Software packages for the C/C++ integrated program development environments such as Eclipse, Codeblock and Microsoft Visual Studio have editors that are integrated into the programming environment. 

    You type a C program with the editor, make corrections if necessary, and then store the program on a secondary storage device such as a hard disk. C program file names should end with the .c extension or save it directly.

    Preprocessing and Compiling a C Program


    Here you give the command to compile the program. The compiler translates the C program into machine language-code (also referred to as object code). In a C system, a preprocessor program executes automatically before the compiler’s translation phase begins.

    The C preprocessor obeys special commands called preprocessor directives, which indicate that certain manipulations are to be performed on the program before compilation. These manipulations usually consist of including other files in the file to be compiled and performing various text replacements. The most common preprocessor directives will discussed soon.
      
    The compiler translates the C program into machine-language code. A syntax error occurs when the compiler cannot recognize a statement because it violates the rules of the language. The compiler issues an error message to help you locate and fix the incorrect statement. The C Standard does not specify the wording for error messages issued by the compiler, so the error messages you see on your system may differ from those on other systems. Syntax errors are also called compile errors, or compile-time errors.

    Source codes in C are saved with .C file extension. Header files or library files have the .H file extension. Every time a program source code is successfully compiled, it creates an .OBJ object file, and an executable .EXE file.




    Linking


    The next phase is called linking. C programs typically contain references to functions defined elsewhere, such as in the standard libraries or in the private libraries of groups of programmers working on a particular project. The object code produced by the C compiler typically contains “holes” due to these missing parts. A linker links the object code with the code for the missing functions to produce an executable image (with no missing pieces). Compile and link a program If the program compiles and links correctly, a file called .out is produced.

    Loading


    The next phase is called loading. Before a program can be executed, the program must first be placed in memory. This is done by the loader, which takes the executable image from disk and transfers it to memory. Additional components from shared libraries that support the program are also loaded.

    Execution


    Finally, the computer, under the control of its CPU, executes the program one instruction at a time. To load and execute the program on a Linux system, type ./a.out at the Linux prompt and press Enter.

    Geeks4Coding

    Contributors

    Popular Posts