2

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;
}
Community
  • 1
  • 1
hnhn
  • 23
  • 1
  • 5

2 Answers2

2

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.

jrs
  • 606
  • 3
  • 5
  • 1
    Thanks, my misconception is now cleared due to your answer. I had used stdio.h in my C program, not iostream.... and scanf() in place of cin. So headers/ functions/ namespace were not the cause of issue. It was mostly due to some goof up in trying to make the age old Turbo C compiler for DOS (for the C version) in a newer OS, that was making me believe otherwise. – hnhn Jan 27 '13 at 04:01
0

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?

Community
  • 1
  • 1
rtcarlson
  • 424
  • 4
  • 13