Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime? For example, in the case that we need some user input to determine the necessary amount of memory space.
The answer is dynamic memory
, for which C++ integrates the operators new and delete.
Operators new and new
In order to request dynamic memory
we use the operator new. new is followed by a data type specifier and -if a sequence of more than one element is required- the number of these within brackets . It returns a pointer to the beginning of the new block of memory allocated. Its form is:
pointer = new type
pointer = new type [number_of_elements]
The first expression is used to allocate memory to contain one single element of type type. The second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:
int * roll_no;
roll_no = new int ;
Operators delete and delete
Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operatordelete, whose format is:
delete  pointer;
The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements.
The value passed as argument to delete must be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).
In this example without using loop it prints the number from 1 to 5,using goto statementcompiler goes to the start tag when goto statement encounters