开发者

How will an expression be stored on the stack?

How will an expressi开发者_如何学运维on like 2*4+6-3/2 be stored on the stack?


Your C++ compiler will store this: 13.

And then the format in which it will be stored is determined by usage. Assigning it to a float makes the compiler store it different than when assigned to an int. I don't doubt the compiler changes ((float) 2*4+6-3/2) to 13.0f.


It won't unless you store it in a variable, i.e. int a = 2*4+6-3/2

A local variable occupies space on the stack, which is taken care of by the compiler. Basically, upon entering a function, a new stack frame is chopped off from the stack memory. Within this 'frame', local variables (amongst other information) are stored.


I don't know if you mean exactly this, but : there is a notation that is very useful when it comes to calculate expressions using a stack, its Reverse Polish Notation.

Here's a link to more information and the implementation :

http://en.wikipedia.org/wiki/Reverse_Polish_notation


The expression will not be stored on the stack. The compiler will put the result of this in .const segment.

When you are inside a function and have

float foo = 2*4+6-3/2; // floating point
int foo = 2*4+6-3/2; // int

will assign (or cast if need) that var in .const section to your variable that is on stack.


The expression will not be stored anywhere, but the result will be. How it is stored depends on how you use it:

float foo = 2*4+6-3/2; // store result as floating point
int foo = 2*4+6-3/2; // store result as int


The only way that 2*4+6-3/2 will be stored on the "stack" in standard C++ is like:

#include <stack>

int main()
{
   std::stack<int> s;
   s.push(2*4+6-3/2);
}

The value 13 is stored in the stack.

Now if, as I suspect, you were not in fact referring to stack but to statically-allocated objects (don't forget, C++ doesn't care where they go physically), then you should consider that "2*4+6-3/2" is an rvalue (a temporary, in this case). Only when assigned to a variable will storage take place. And then, the literals will be evaluated to produce the single value "13". The mathematical expression will not be kept.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜