Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is declaring a variable an instruction

Tags:

c++

Is declaring/assigning a variable in a high level language such as c++, an explicit instruction?

e.g. x = 5;

It would be handled by the loader, and treated as state information, correct?

It is not an instruction, but a state object, as opposed to something like a for loop, which is an instruction, which makes it's way to the cpu ?

edit: OK, to clarify a bit more. I am not talking about optimisations. Assume none. I am talking about the end result of a compiled program, in an executable file format. Under the circumstances where the compiler decides not to use the MOV instruction, will the data 5 exist within the executables files data segment, or somewhere else?

Is it possible for the 5 to exist as data without being an instruction, with that data later on being loaded into memory? Or, in general, will x = 5 result in a mov instruction when the program is executed.

like image 846
Joshxtothe4 Avatar asked Dec 17 '22 07:12

Joshxtothe4


2 Answers

Are you asking if a variable declaration will translate into an assembly instruction in the same way an add or delete would? If so, then the general answer is there is no direct translation into assembly.

There may be instructions which facilitate the declaration of a variable such as updating the stack pointer to make space for a variable. But there is no x86 assembly instruction which says declare variable of this type on the stack.

Most of my experience is with x86 and amd64 chips so there could be instructions on other processors but I am not aware of them (but would be curious to read about them if they did exist).

Variable assignment is a bit different. The general case of x=5 will translate to some type of assembly instruction (writing the value to a register for instance). However with C++ it's really hard to be specific because there are many optimizations and chip specific settings that could cause a particular line to have no translation in machine code.

like image 197
JaredPar Avatar answered Dec 19 '22 19:12

JaredPar


It depends on how it is used.

Generally, the compiler will try to make every line as low-impact as possible.

If this is used in only one place, you can bet your buttons that it is hard coded in the machine code, rather than wasting space on the stack.

If it is used for math or algorithmic operations, and its value may change, space for the variable may be allocated on the stack. Then again, if it used frequently enough, the compiler may just leave it in a register.

The answer is: it depends. Compile it and view the result with a debugger's machine code window.

One possible actual translation:

MOV AX, 5
like image 20
John Gietzen Avatar answered Dec 19 '22 20:12

John Gietzen