Oridinary (automatic) variables in C++ use stack or heap?
Possible Duplicate:
What and where are the stack and heap?
A vary basic question, please forgive my ignorance. Please let me know whether a simple variable declaration in C++ for an ordinary (automatic non-static and non-global) variable for example.... float x; within the scope of a function, say main() uses stack or heap (free store) memory? I am asking this because code such as the one given below works in C++, but not in C. Thanks in advance.
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
if(a < b)
{
int c = 1925;
float d = 0.7;
}
else
{
double e = 889.7;
short f = 35;
}
return 0;
}
These variables will be created on the stack, and destroyed when they leave their containing scope. For example, when the if statement terminates, c and d will no longer be available as they will have gone out of scope when they hit the first closing brace "}".
The reason this works in C++, but not C, doesn't have to do with stack vs. heap allocation. The "using namespace std", and the iostream.h file you've #included only exist in the C++ standard template library! See http://www.cplusplus.com/reference/ to check out what's available in C vs. C++.
Heap allocation works when you use the new operator, which returns a pointer to a newly allocated object on the heap, and will not be destroyed until you explicitly call delete on the pointer.
Variables declared in the fashion you've described are stored in the stack.
See this response for more details: What and where are the stack and heap?
链接地址: http://www.djcxy.com/p/2270.html上一篇: 返回指令堆栈中的指针