In C++ you have three places where you can store variables:
* Register
* Stack
* Heap
Each of them have their own advantages and disadvantages which I'll cover here.
Nowadays the register is not often used (correct me if I'm wrong) , but when you can really use it (at very low level), it's the best place to store small variables that you will use a lot and that need to be fast, that is because the registers are directly managed by the processor, it doesn't have to access the RAM so it's very fast, however, you won't be able to store data that is too big and you have a limited amount of registers.
When you create a variable in a function and don't add anything else but the type, the variable is stored in the stack (this type of variables are called auto (ex: auto int myint = 0), and is the default for all local variables). Think of the stack as a pile of papers, you can read the top of the pile, you can trash the top of the pile, you can move the top paper and read the next one, etc. So, the stack is relatevly fast and can be used for most things without any problems, and in most cases, it's best way of storing variables, they are created and initialized when the program gets to the block where they're defined and are destroyed when the block ends. However, as everything, it has it's limitations, for example, you can't have too many (or too big) auto variables because you'll overload the stack, which isn't good hehe.
And finally, heap variables. This variables are stored on plain RAM, the good thing is that you have a lot space (well this depends on the ammount of RAM available). This type of variables are created with the operator new and destroyed with delete or free, they don't die when the function ends which can make memory leaking problems, but it's the best place for storing big variables and actively controlling their lifetime.
Missuses of the types of variables:
When you make a function that returns a pointer, for example:
Code:
//-----------------------
char * myfunc( const char some_arg )
{
char myvar[] = "Some string";
return myvar;
}
//-----------------------
The variable myvar is destroyed at the end of the function so the the pointer will be pointing to a non-existing locations. This might work as expected, my not work or might just exit giving you a memory violating error because you're triying to read protected memory. This is one of the worst errors a programmer can make, because as I said, it might work some times and he/she won't notice it until it becomes a huge problem and has to spend hours debugging the application.