Both variables num1
and num2
are automatic variables which means they are allocated on the stack automatically. The variables have function scope. Once the function they are defined in returns, they are deallocated from the stack, i.e., they cease to exist and trying to access them is undefined behaviour.
A variable which is defined inside a function (including function parameters) and which is not static
is an automatic variable. It is automatically created on the stack when the function is called and is destroyed when the function returns. Therefore, it is local to the function, i.e., it has function scope.
A variable which is defined outside of any function is called a global variable. Static variables and global variables have static storage duration
which means they are neither allocated on the stack nor on the heap but in text segment (if they are const
) or data segment of the program's memory layout or even into its own memory segment on most modern machines. The important thing to note is that the memory is allocated once when the program begins execution and is never freed because the lifetime of global and static variables extends across the entire run of the program. Also, global and static variables are default initialized to zero if not explicitly initialized. Read this - The initialization of static variable in C.
You cannot create a variable on the heap, i.e., an indentifier cannot be bound to a memory location on the heap. You can allocate memory on the heap and store a pointer to it in a variable but the variable itself is not on the heap. If the variable is local and non-static, it's on the stack else it's in the text segment or data segment. Read this for more details - Memory Allocation in C Programs