Toggle Menu

C++ Basics


Table of Contents

Variables

Variables are used to store a value. The name of a variable is called an identifier, which are case-sensitive.
Here are some types of variables:
  • short (short int)
  • int
  • long (long int)
  • float
  • double
  • long double
  • char
  • bool
  • enums
New C++11 Types:
  • auto: Deduces type of variable based on expression. auto x = expression;
  • decltype: Determines type of expression based on provided arguments. decltype(x*3.5) y; declares y as a double.

Literals

  • Constant. Cannot change values during execution.
  • We "literally" typed them into the program.😉
  • e.g. 2, 5.75, 'Z', "Hello World!"

Declaration

Every variable must be declared before it is used. This tells the compiler what kind of data is being stored in the variable so it can allocate the required space for it. Uninitialized, declared variables have a default garbage value set to them.
Syntax for variable declaration: Type_Name Var_Name_1, Var_Name_2, ...;

Assignment

Evaluates the right-hand side of equal sign and sets the variable on the left-hand side equal to the value.
Syntax for variable assignment: Variable = Expression;

Assignments can be chained. e.g. n = m = 2
This is equivalent to n = (m = 2). First, m is set to 2, this expression is evaluated to 2 which is then assigned to n.
If a variable is assigned a value at the time of declaration, it is being initialized. There are 2 methods of initialization:
  1. int count = 0;
  2. int count (0);