Sunday 4 September 2016

Storage Bindings For Variables

Storage Bindings For Variables


This post is meant to describe variables into four different categories based on their Storage Bindings. The Binding categories will be
  • Static Variables
  • Stack Dynamic variables
  • Explicit Heap Dynamic variables
  • Implicit Heap Dynamic Variables

Static Variables
Static variables are bound to memory cells sometime before execution and remain bound to the same memory cells until program execution terminates. This means values are assigned to the memory cells of a variable before the execution of a program begins. Global variables are usually static variables although a lot of languages allow subprograms to have static variables called “local static variables”. Class variables in a lot of language implementations are usually static variables. Class Variables are created sometime before program execution begins.
Strengths
-Static Variables are fast. They can be addressed directly unlike other variables that require indirect addressing which is usually slower.
-Static Variables are history sensitive. They always remember.
Weaknesses
Static variables reduce programming flexibility. They do not support recursion.
Example of a Static Variable In Java
class StaticVariableEg 
{ 
   static int count=0; //count is a static variable 
   public void increment() 
   { 
       count++; 
   } 
   public static void main(String args[]) 
   { 
      StaticVariableEg obj=new StaticVariableEg(); 
      obj.increment(); 
      System.out.println(obj.count); 
   } 
}
The Implementation of static class variables in Java is similar to that of C# and C++.
C and C++ have a static specifier that can be used in variable definitions in a function to make the variable static.
Stack Dynamic Variables
In stack dynamic variables, storage bindings are created during the “elaboration” of a variable, Not when execution starts but when execution gets to the variable(elaboration). Stack Dynamic variables are created at run time when execution has begun. Like static variables, deallocation cannot be done until execution is complete. In stack dynamic variables both allocation and deallocation is done from the run time stack
Strengths
Stack Dynamic variables are more flexible than static variables. They can be used in recursive subprograms.
Weaknesses
Stack Dynamic variables are not history sensitive. Their values can permanently change during execution.
Stack Dynamic variables are slower than static variables because of the incurred overhead in allocation and deallocation of variables and also it requires indirect addressing.
In Java, C++, and C#, variables defined in methods are by default Stack dynamic
class StackDynamicEg 
{ 
     void counter() 
     { int count = 0; //Stack Dynamic variable 
     } 
}
Explicit Heap Dynamic Variables
In Explicit Heap Dynamic variables allocation and deallocation are done at run time by explicit instructions written by the programmer. Allocation and Deallocation of explicit Heap Dynamic variables is done from the heap. They are created with Pointers and Reference variables.
Strengths
They are very memory prudent.
They can be used to create dynamic data structures like Linked Lists and Trees that can grow and shrink during execution
Weaknesses
They require pointers which are relatively more complex to implement
They are slower than static variables because of the incurred overhead in allocation and deallocation of variables
In C++
int *intnode; // Create a pointer 
intnode = new int; // Create the explicit heap-dynamic variable 
delete intnode; // Deallocate the heap-dynamic variable
In Java all objects are explicit heap dynamic variables and are accessed through reference variables. In contrast to C++, Java does not allow explicit deallocation of variables, deallocation is done implicitly by the garbage collector.
Implicit Heap Dynamic Variables
In Implicit Heap Dynamic Variables, allocation and deallocation are done only when the variable is assigned a value at runtime. Allocation and deallocation are done at runtime from the Heap.
Strengths
  • They are very flexible
  • They make optimum use of memory
Weaknesses
  • They are very slow
  • They are not history sensitive
In Python
#!/usr/bin/python 
str = ["Java", "Python", "C++", "Delphi", "Fortran"] #implicit heap dynamic variable 'str' is created at runtime 
print str 
str = 5 #implicit heap dynamic variable which was previously a list of length 5 is now an integer 
print str


Storage Bindings For Variables

Please, this topic is open for discussion. Let us talk more on implementation in other languages I didn't mention or challenges encountered in implementation. I recommend Concepts of Programming Languages (11th Edition) 11th Edition by Robert W. Sebesta to anyone who wants an elaborate explanation of the topic. It is a really great book.

Related Posts

Favorite Languages For Numerical Analysis & Scientific Computation

5 comments:

  1. Рейтинг онлайн-казино включает клубы, предлагающие хорошо обдуманную мотивационную программу. Посетителей ждут неоднозначные призы — приветственные, бездепозитные, фриспины, релоад. Некоторые порталы презентуют поощрения по выходным, дням, ко деньку рождения. Кроме этого игровые автоматы с бездепозитным бонусом, поддерживают программу преданности со статусами, дозволяющую получить дополнительные подарки за активность. Одновременно ведутся турниры, лотереи, сезонные промоакции. Благодаря данному посетители выигрывают больше, шансы превосходно развлечься, вложив колличество.

    ReplyDelete
  2. Рейтинг онлайн-казино включает клубы, предлагающие хорошо продуманную мотивационную программку. Посетителей ожидают разноплановые призы — приветственные, бездепозитные, фриспины, релоад. Некоторые порталы дарят одобрения и, дням, ко дню рождения. Кроме этого игровые автоматы с бездепозитным бонусом, поддерживают программку лояльности со статусами, позволяющую получить вспомогательные презенты за активность. Одновременно проводятся турниры, лотереи, сезонные акции. Благодаря данному посетители выигрывают больше, шансы хорошо рассеяться, вложив минимум.

    ReplyDelete
  3. Players can even win free spins within every individual game. Its slot machines common greater than $370 a day in revenue every, greater than twice the take of Vegas machines. While there are some obscure gestures course of|in course of} New York City theming , this is not a haunt for high-rolling "motion" gamblers, because the trade calls them – stay games are still unlawful in New 코인카지노 York. This, rather, is a sanctuary for "escape" gamblers, the kind who are more interested, Schüll says, in spending time on a machine than in getting massive wins.

    ReplyDelete
  4. В сети большущее руководств купить ссылки для продвижения сайта в яндексе по верному выбору доноров, хотя практически во всех указан лишь перечень метрик, коие нужно испытывать. Мы рекомендуем этого всего уделять на качество плана. Даже в у сайта больной DR, гиперссылка с него может быть полезной.

    ReplyDelete
  5. На 1 странице выдачи закупить ссылки для продвижения сайта этой машины 4 вебсайта – реклама, 3 последних – реклама. Есть всего 10 ведущих ресурсов, данном пользователи часто навещают лишь 1-ые два-три из их. Попасть в ТОП без впечатляющей ссылочной массы, в соперниками являются тогдашние веб-сайты со обилием ссылок, нереально.

    ReplyDelete

About Me

My photo
My name is Solomon Ubani, I'm a computer scientist. I have few years of programming experience. I am happy to learn from you.