#include<iostream>
using namespace std;

void prin();//statement a
main()
{
    int x; //statement 1
    x=34;//statement 2

    return 0;
}

I wanted to know if the variable x is allocated memory in statement 1 or in statement 2. Its a long time doubt and no one really gives a clear and confident answer to this one.
Also does declaration of a function allocate memory for it?

1) A local variable is allocated on the stack when its function is called.
2) Nothing of the like needs to happen. It's just an information for the compiler that such a function does exist somewhere.

Its a long time doubt and no one really gives a clear and confident answer to this one.

Because there's not a clear answer. Different compilers are free to do it in different ways provided the effect is the same. However, typically local variables will all be allocated to the stack frame when the function is called, regardless of their scope within the function.

Also does declaration of a function allocate memory for it?

Functions aren't allocated memory[1]. Calls to a function typically cause a stack frame to be allocated, which contains things such as the the parameters, local variables, and return address. But that's different from the declaration/definition of the function.


[1] Unless you want to count the "text" segment where the function's implementation is stored. While loading an executable does indeed allocate memory, I suspect that's not what you meant with your question.

statement 1: assign memory location for variable x, now variable x contains "garbage" value.

statement 2: assign value to variable x which is 34.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.