Declaration and initialization

Until this point we have seen that a user/programmer can create a couple of variables and assign them a certain value, in respect of their data type. We have left out some terms which are useful to know when making new variables.
The first one is variable declaration. It is simply the process of stating the variable type and its name. For all of the types mentioned above you can just do that, with a few caveats, or rules you need to follow:
  • The name of a variable can be any combination of numbers, letters and the symbol “_” but:
    • The variable name mustn’t start with a number
    • The variable name can start with an underscore
    • The variable name must be unique – it cannot be a name of any keyword used in C++ or a name of a variable which is already defined
    • Variables with two or more words must be separated with “_” (space is not allowed)
The second one is variable initialization. It is simply the process of giving an already declared variable a value. The process of initialization can be indeed done while the variable is being declared (this process combined is called a variable definition) or it can simply be done after.
int a; // Declaration of a variable "a"
float b = 5.5; // Declaration and initialization (definition) of a variable "b"
a = 3; // Initialization of a previously declared variable "a"

double _c = 2.0; // This is OK! Declaration and initialization (definition) of a variable "_c"
int 8ac = 55; // Error! The variable name mustn't start with a number

float speed_of_light = 299792458.0;

This leaves us with a final question in this topic: If we declare a variable but don’t initialize it, what value is stored inside? In C++, the compiler was written in such a way that when you declare a variable but don’t initialize it, an implicit initialization may or may not take place with some predefined value, for example, an int gets set to 0, but that’s not always the case! You might get some garbage value which was previously stored in that memory location. That’s why it’s always a good practice to initialize all your variables before using them.

Leave a Reply