Wednesday, February 24, 2016

What is the meaning of dynamic and static in the context of programming?

Dear Folks !


The literal meaning of dynamic is something in motion.That's why anything we do at run-time of the program, we call it as dynamic. For instance dynamic initialization, it is the process if assigning a initial value to a variable at run-time.
Dynamic:                                
          

Where as static is, any thing that is stationary(not in motion or at rest),  Here in programming, anything done before run-time is called static. That is normally compile-time of the program.
Static:


In C we use :
 scanf(): to read values for variables at run-time of the program
 gets(): to read strings at run-time and getch() to read characters at run-time.

In C++ we use:
 cin object to read at run-time(console in that is reading from keyboard)

Similarly, dynamic allocation of memory, is allocating memory to variable at run time of the program. This has the advantage of using exact required amount of memory(No wastage, No shortage of memory).

In C we use malloc() function to allocate memory at run-time of the program.For instance if we want to allocate memory for N integers at runtime, then we use following code snippet in C language.

int *p;
int n;
printf("For how many integers do you want to allocate memory\n");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));

In C++, same job is done, using new operator, as shown below.

int *p;
int n;
cout<<"For how many integers do you want to allocate memory\n";
cin>>n;
p=new int[n];

This allocates memory at run-time, so it is dynamic initialization.




The examples for compile time activities are,static initialization of variables, which is the compile-time initializaton  of variables. The other examples could be, static allocation, static binding/linking etc.

Static allocation, is the scheme of memory allocation, in which the amount of memory to be allocated must be specified before run-time, i.e it should be known in advance, before run-time of the program. 

In C/C++, arrays use static allocation of memory. The major disadvntage of static allocation is that, we may fall short of memory , or else we may end with waste of memory. 
If you have any queries, you are most welcome... Please give your feedback about this post and reply through the blog itself.



1 comment: