Mar 8, 2017

Compile time constants and Run time constants

Compile time constants:

These are the primitives(int, char, byte and short) and strings that are declared with keyword final and initialized at the time of declaration (value should be known to the compiler at the compile time).

For example:

public final int x = 10;            -> 1

Here the variable x is declared with keyword final and initialized at the declaration time. It is called as COMPILE TIME CONSTANT (Since, the identifiers that are declared as final and initialized once, their value cannot be changed later).

If we look at another case,

public static final int x = 10;     -> 2
            
This is also a COMPILE TIME CONSTANT.

The basic difference between 1 and 2 is static. It means that variable is related to the class but not object.
      1 -> It allocates the memory for every object with the given value.
      2 -> It allocates the memory once for the whole class and that can be accessed with either the class name or with the objects.
  • These Compile time constants are used in switch case statement.
For example:

public final int x = 10;
public final int y;
y=6;
switch(a+b){
case x:                 // no error
case y:                // compile error
}

Let us discuss, how the case condition works based on the values?

The JIT compiler transforms the switch statements into JVM bytecode tableswitch or lookupswitch for which the values must be COMPILE TIME CONSTANTS and also they must be unique.

In the above case, x is a compile time constant, since it's value can be determined at the compile time, whereas y is a constant variable but not compile time constant, since it may or may not be initialized in the code. i.e. there can be any other statements in between the initialization.

if (a == 1) {
    y = 6;
} else {
    y = 4;
}

From the compiler point of view, it is like using a variable that might not be initialized. Hence it is called as RUN TIME CONSTANT (Since it is initialized at RUN TIME only).

For example:

public static final int x = getValue();

Here, the compiler won't treat it as COMPILE TIME CONSTANT since the value returned by the method may or may not be assigned to the variable x. It is treated as RUN TIME CONSTANT.


Mar 16, 2016

My Youtube Channel - COMSCIGUIDE


Interview Puzzles :

These are the common questions that are asked in the HR interview. As puzzles are updated from interview to interview, in this playlist, recently asked puzzles are updated with the removal of others. 

For full playlist of Interview puzzles videos :
  

24 standard interview puzzles:  


Aptitude training playlist link : 


For C and C++ questions, that are asked in the interviews, go through the posts in the link :  


For more videos, my youtube channel : 


This video helps you how to prepare for an interview.

How to prepare for an Interview

Oct 23, 2015

What is Polymorphism



   Before going to that, I will explain a real world example.

If you give an instruction "cut" to three different people – a hair stylist, a doctor and a movie actor. How do they respond?  The hair stylist cuts the hair.  A doctor will cut the patient’s body for surgery, a movie actor will stop acting. The message (cut) is same to all three objects (actor, hair stylist and a doctor), but they three respond in three different ways. This is called as Polymorphism.

Polymorphism: Poly – Multiple and Morph – Form

Polymorphism refers to the ability of two or more objects belonging to different classes to respond differently to the same message in class specific ways.

It means the ability to take more than one form. An operation may exhibit different behaviour in different instances. The behaviour depends on the types of data used in the operation. For example, consider Addition operation. For two numbers, the operation will generation sum. In case of two strings, it will generate a third string with concatenation. Thus, polymorphism allows objects with different internal structure to share same external interface, though specific actions associated with each operation (function) may differ.

How is polymorphism implemented ?
·       The fundamental idea of polymorphism is that a compiler doesn’t know which method (i.e. base class implementation or derived class implementation of a method) to call during  the compile time.  It only knows during run time (based on the object). This is called as “Late Binding”.  This type of polymorphism is called as “Run time Polymorphism” or "Polymorphism by Inheritance"
·       Polymorphism can also be achieved through method overloading.  During the compile time itself the compiler knows which method to execute. This is known as “Early Binding”. This type of polymorphism is called as “Compile time Polymorphism” 

There are two types of polymorphism:

1. Compile time Polymorphism

2. Run time Polymorphism

Compile time Polymorphism:

One function - multiple purpose
or
 In short, Many functions having same name but with different function body. For every function call, compiler binds the call to one function definition at compile time. This decision of binding among several functions is taken by considering formal arguments of the function, their data type and their sequence.

Example :

void f(int i){cout<<"int";}
void f(char c){cout<<"char";}
int main()
{
   f(10);
   return 0;
}
Output: int

Run time polymorphism:

C++ allows binding to be delayed till run time. When you have a function with same name, equal number of arguments, same data type in same sequence in base class as well derived class and a function call of form:
base_class_type_ptr->member_function(args);
will always call base class member function. The keyword virtual on a member function in base class indicates to the compiler to delay the binding till run time.
Every class with atleast one virtual function has a vtable (virtual function table)  that helps in binding at run time. Looking at the content of base class type pointer, it will correctly call the member function of one of possible derived / base class member function.
Let’s say that we have a base class called Class A and it has a over-ridable method called print which prints all the attributes.  Then by inheritance concept, all the derived class will inherit this print method. The derived classes can either override the print method or use the print method from base class.  So, all the objects of base class and derived class have a method called print and they respond differently to a message based on its class implementation.

Example:

class Base
{
public:

    virtual void display(int i)
    { cout<<"Base::"<<i; }
};

class Derv: public Base
{
public:

    void display(int j)
    { cout<<"Derv::"<<j; }
};

int main()
{
    Base *ptr=new Derv;
    ptr->display(10);
    return 0;
}
Output:  Derv::10

As the base class has virtual function, the statement

Base *ptr=new Derv;
will point to the derived class and execute the display function that has been defined in the derived class. If virtual keyword is not declared, then the base class display function will be called.




Filed under  | 

Sep 25, 2015

Programs that work in C and not in C++


1.
int main()
{
                       int a = fun();
            return 0;
}
int fun()
{
            return 2;
}

As the function prototype is not declared before the function is called, it gives an error in C++. But in C, it works fine.
2.
int main()
{
            const int a;                
            return 0;
}
               
            In C++, the const integer should be initialized at the time of declaration only.
3.
int main()
{
            int c;
            void *b=&c;
            *((int*)b)=10;
            printf("%d",*((int*)b));
return 0;
}

Here the void pointer points to an integer.  For typecasting to int pointer, we need not to use                 explicit type cast as we do in C++. In C, type casting is done through implicit typecast.
4.
int main()
{
            int const a=10;
            int *p=&a;
                       return 0;
}

In C++, only the const pointer can point to the const integers. In C, either const or non-const pointers can point to that object.
5.
int main()
{
            int new =10;
printf("%d",new);
return 0;
}

In C++, new, delete, explicit are Reserved words. As reserved words cannot be used as variables in C++.
6.
int main()
{
            char *p=333;
            printf("%u",p);
            return 0;
}


            In C++, char pointer  can’t point  to an integer variable.


      Also see 

                       1.  4 Pillars of OOP concepts
                       2.  Associativity of Operators 
                       3.  Graph Terminology



Filed under ,  | 

Aug 9, 2015

What’s the difference between malloc(),calloc() and realloc() ?


        In c language there are 3 terms that are used for dynamic memory allocation. If we allocate the data through dynamically, then that would be available until the program terminates (like global variables).

        we can have choice when to allocate and de-allocate. De-allocation can be done using free() function.
1) Malloc() :
        
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.

                void *p = malloc(sizeof (int))
  • As it a void pointer, we can’t directly dereference it .

                like *p = 2;      // gives an error.
        
  • Before using, we have to typecast to the system defined data types ( int, float, char etc ).


        int *q = (int* )p ;
        *p = 10;           // no error

  • After allocating the memory, if we won’t initialize the values, then garbage values will be present.



         
Calloc() :
        Calloc() also allocates the blocks of memory and also initializes the allocated memory to value equal to 0 ( like in malloc() garbage values will be present). It also takes 2 function arguments as inputs.

        1) Number of blocks.
        2) Size of each block.

                int *p = (int*) calloc(n, sizeof(int))

Example:
int *p = (int*) calloc(25, sizeof(int))

This statement allocates contiguous memory space for an array of 25 elements each of size of int, i.e. 4 bytes.
  • calloc can be defined using malloc function as follows :

                char *p = (char*) (10* malloc( sizeof(int)));
                memset(p, ’0’ , 10);

The 10 memory address locations will have value 0.
Realloc() :
        realloc() is used to reallocate the memory for the given pointer either to increase the memory block or decrease the memory  block.

Syntax :

                int *b = (int*) realloc( oldblock, new memorysize);
  • It first looks whether the old block can be extended if we want more memory. If it is not possible, then a new block of memory is allocated and the old values are copied.
  • After copying the old block of memory into the new memory location, old one is automatically deleted.

  • If we reduce the size of memory block, then remaining memory is de-allocated automatically.
  • free() statement can also be done using realloc().

int *b = (int*) realloc(b, 0);
  • malloc() function can be done using realloc().


int *b = (int*) realloc(NULL , n*sizeof(int) );

SEE ALSO :






Filed under ,  | 

Aug 8, 2015

Dynamic memory allocation (Stack vs Heap)


          Application’s memory – The memory that is assigned to a program or application while running is divided into 4 segments.

Heap
(dynamic allocated)
Stack
 (functions and local variables)
Global / Static
Code ( text )
(instructions)

·       The amount of memory that is reserved for main function is called as Stack Frame.
·       Heap size is not fixed.
For example :
#include<iostream>
using namespace std;
int z;                 // global variables.
int mul(int a,int b)
{
int c;
c=a*b;
return c;
}
int init()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=mul(a,b);
return c;
}
int main()
{
z= init();
printf("%d",z);
return 0;
}

While the program mul() is executing, the stack will have memory assigned as mentioned below :

mul() a, b, c
scanf()
init() a, b, c,
Main

The program starts with the main() function and is pushed into the stack. In main init() function is called next, so the main function stops executing and init() function resume and its variables are also declared in its memory declared for init(). Similarly for others.
·       The size of the stack for a method is calculated when the program is compiling. At any time, the function at the top of stack is executing, remaining are idle.

·       Once the function returns, the memory in stack is popped out and next function below it, will start executing.

·       Global variables are declared outside the stack are allocated in separate global memory section. So by this we can access global variables anywhere in the program, until it terminates.

·       Local variables declared inside each function, are allocated in their functions stack memory and also limited to those functions only.

·       When main functions returns, the program terminates and the global variables are also cleared.

·       If the stack calls goes beyond the memory, then an error will occurs i.e. stack overflow.

·       The size of Heap is not fixed. It will grow as long as it don’t run out of memory in the system itself.

·       we can keep the data in the heap till what time we need i.e. we can have control on the allocation and de-allocation.

·       Heap is also called as Dynamic memory and it’s allocation is called as Dynamic memory allocation. It’s different from heap (data structure).

In c, There are 4 functions that are used in dynamic memory allocation.

They are
       1) malloc()
       2) calloc()
3) re-alloc()
4) free()
In c++, there are extra 2 more operators including above.

New and delete

For example:
int main()
{
int a;
int *p, *q;
p = (int*)malloc(sizeof(int));
*p = 10;
q = (int*)calloc(3,sizeof(int));
*q = 10;
*(q+1) = 20;
*(q+2) = 30;
return 0;
}



·       Free(p) – It will deallocate the memory that is assigned to p.
·    p will have only the starting address of that memory block.

·       If we won’t mention free(p), in c or delete in c++ , the data will be still available until the program terminates (act like global variables ).

Recent posts :