top of page

Declaring & Initializing Variables

Before using variables within our programs, we must first declare them. There are generally two types of variables we will commonly initialize; these include constant variables and normal variables. Constant variables are variables which hold a fixed value and are not subject to change. A variable defined normally is subject to change throughout the program.

The initialization and declaration format for a standard variable is: varType varName = value;

For a constant variable we will use: const varType varName = value;

Below is an example of a constant variable and a normal variable being defined and initialized.

decandintvar1.png
decandintvar2.png

Upon execution the variable is set to the later value as it is subject to change while the constant cannot be changed or we will get an error.

If we try to set the constant variable equal to another number, we will get the compiler error "assignment of read-only variable 'constant'".

Declaration vs Initialization: Declaration is the statement which defines the variable (int var;) whereas initialization is setting that variable equal to something (var = 5;) We can however declare and initialize a variable in one line (int var = 5;)

Examples:

decandintvar3.png
  • Twitter
  • LinkedIn
  • discord-logo--v2
  • kisspng-github-pages-logo-repository-fork-github-logo-1-magentys-5b69de71b51265

Dragon Eye Intelligence LLC

bottom of page