What is a variable?

Asked

Viewed 983 times

27

We always use variables all the time in codes. Is it the same thing we learn in mathematics? How does the variable work?

3 answers

24


Essentially variable in computation is the same as in mathematics, we only use it in a slightly different way, at least the way we learn about variables in school. Variable does not need to be part of a formula as it usually happens in mathematics.

Definition

Variable is a name for a value. It is a indirect that we use to facilitate our coding work.

Computers don’t recognize variables, this is a high-level concept, it’s an abstraction created by humans to better express a concrete value.

For the computer there are memory positions where values are stored and this is controlled by the hardware and operating system.

In general operating systems work with a virtual memory system where each process "sees" the memory as if it were all its own. On the other hand, he can’t access parts of his memory that don’t belong to him. Real memory is a complete mess, but for the process it looks like a clean sequence.

The code will access these addresses as needed. Data may be:

  • in a static area that cannot be written,
  • in pile area enforcement that has control automatic of lifespan,
  • and in the general area that is used for dynamic allocation and life time should be managed by your code (or framework who uses).

The machine code only accesses the addresses purely. So much so that in Assembly we only use addresses. Internally variables disappear and give way to memory addresses.

Variables are only names for memory positions where values are stored. We can also say that variable is a storage location.

Names

The name of the variable that is known as identifier or even symbol is a reference to a value either directly or indirectly. This reference is known by its source code, but will disappear after the compilation or interpretation of this code.

In mathematics we use variables of one letter. In programming we usually give more meaningful names since we work with very different problems, outside the standard of mathematics and we often have many variables in use.

Some variables don’t exactly have names, but rather index. This is the case of a array. Each element of array is a variable that is accessed by its index together with the variable that references all the array. A calculation is made to find the memory position from the initial position of the array and shifting the index.

Variables may be within a structure. There is also a displacement as in array, but unlike the array whose elements are homogeneous (same type, same size), a data structure is heterogeneous.

In the names one can usually use letters, numbers and some symbols, mainly the _. Starting with numbers is usually prohibited since it would create ambiguity with literal numbers. Most non-alphanumeric characters are prohibited because they would confuse with operators and other language constructs, including space that would eventually separate the name into two. Some languages restrict to very few symbols and any Unicode character can be used.

Invalid name:

valor total
data-vencimento
12dias

Some languages do not differentiate between upper and lower case.

It is common to establish conventions for names. It has language that made it have its own semantics in the code.

Multiple names can reference the same storage location. Obviously if the value in this location changes, all variables will have their value changed (roughly).

Corollary

Variable is a design pattern (Pattern design) so used, so simple, and so present in languages that no one sees it like that. It’s a standard to access a memory position. This pattern makes independent name and value. It creates several opportunities to express complex algorithms in a way powerful and flexible.

When we say "I will print the variable", in fact it always means "I will print the value referenced by this variable".

There are cases where the value is referenced directly by the variable, are the variables by value.

There are cases where the value is referenced by a pointer whose variable reference is the variables by reference. In this case the real value of the variable is the memory address that indicates where the value you want to access is.

It is common to refer to the value as a object. This has nothing to do with object orientation.

The value of a variable can eventually be known only during execution. Its value can be changed during the execution of the code, except something in it that creates some impediment. Some variables can be declared as read-only, so the value is "changed" only once in its creation.

Variable differs from constant mainly because the second one does not allow its value to be changed throughout the execution of the code. It is possible that a constant is already replaced by its value by deleting the reference.

Variables can be accessed (reading) or assigned (writing).

Variables usually have scope.

In statically typed languages a variable will have a type throughout its existence (there may be exceptions). In dynamically typed languages the variable has the type of value it references at that time.

Parameters, for all intents and purposes are variable.

Most languages require a variable to be declared before using it. A statement is an indication for the compiler to reserve memory space for the variable. During the declaration it is already possible to assign a value.

Today there is virtually no language that requires the variable to be declared at the beginning of its scope. In the past this was necessary to facilitate for the compiler, but today it manages to detect all statements anywhere in the scope and makes the reservation at the beginning of it.

Most variables are not mandatory in fact, but not using them can make it very difficult for the code to do, repeating operations and piling things up. While they can be useful, it is common for lay programmers to use variables without the slightest need.

In some cases variables can be used to better document the code. It is a way to name a formula.

14

Variable is a name that holds a value, as Maniero very well explained in his reply. This value can be of various types and the variable has visibility scopes that depend on where it was originally declared within the code.

The most common types of variables are: integer, real number, text, value vectors or collections, and boleane. In most languages you will find these names in English as int or integer, float, string, array/vector/list/Collection etc and bool or Boolean.

In some strongly typed languages you will need to specify the type at the time of the variable declaration. Eg: Java or C++. In other languages, low-typed calls, this type specification at variable startup time will be unnecessary and the type will be analyzed dynamically during runtime. Ex: PHP and Javascript.

Variables declaration in general, already initialized:

datable type = recoverability;

Note: Semicolon marks the end of instruction in a large number of languages.

Examples of variable declaration in strongly typed language (in generic algorithm, as it will be different in each language):

int numero = 178000;

string nome = "Maniero";

float salario = 8000.00;

array frutas = ["banana","maçã","pera","uva"];

bool estaChovendo = false; //accepted as false or true, 0 or 1

Scope of variables

Depending on where the variable is declared, other parties may or may not access/use it.

Crass example:

// variavel declarada globalmente
variavelglobal = "essa var pode ser acessada de qualquer lugar";

// Bloco de código, como uma função
{
   print variavelglobal; // ok
   
   variaveldentrodefuncao = "outra variável, só que esta está sendo declarada dentro de uma função";
}

print variaveldentrodafuncao; // erro, pois essa variavel só existe no escopo onde foi declarada, ou seja, dentro da função

See detailed explanation by following the link scope of Maniero’s response.

  • 3

    Cool, always good to have other answers.

0

A variable is a name given to a space in memory ram that will record a data to be used by you in your program.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.