DEV Community

Igor
Igor

Posted on

Variables in C++

  • If we had to program using the specific memory locations of a Random Memory Access (RAM), it wouldn’t be a lot of fun, and we’d likely have a lot of programmer errors.
  • A variable is an abstraction for a memory location
  • Allow programmers to use meaningful names and not memory addresses
  • Variables have
    • Type - their category (integer, real number, string, Person, Account…)
    • Value - the contents (10, 3.14, “Tim”…)
  • Variables must be declared before they are used
  • A variables value may change
age = 22;        // Compiler error
Enter fullscreen mode Exit fullscreen mode
int age;

age = 22;
Enter fullscreen mode Exit fullscreen mode

Declaring Variables

💡 VariableType VariableName

int age;
double rate;
string name;

Account franks_account;
Person james;
Enter fullscreen mode Exit fullscreen mode

Naming Variables

  • Can contain letters, numbers, and underscores
  • Must begin with a letter or underscore (_)
    • cannot begin with a number
  • Cannot use C++ reserved keywords
  • Cannot redeclare a name in the same scope
    • C++ is case sensitive
Legal Illegal
Age int
age $age
_age 2022_age
My_age My age
your_age_in_2000 Age+1

Style and Best Practices

  • Be consistent with your naming conventions
    • myVariableName vs my_variable_name
    • avoid beginning names with underscores
  • Use meaningful names
    • not too long and not too short
  • Never use variables before initializing them
  • Declare variables close to when you need them in your code

Initializing Variables

int age;      // uninitialized

int age = 22; // C-like initialization

int age (22); // Constructor initialization

int age {22}; // C++11 list initialization syntax
Enter fullscreen mode Exit fullscreen mode

Global Variables

  • Variables declared within the curly braces of the main function are called Local Variables because their scope or visibility is limited to the statements in the main function that follow the declaration of the variable. This is generally what you want to do.
  • However, sometimes you see variables declared outside of a function, these variables are called Global Variables and they can be accessed from any part of your program.
  • Unlike local variables, global variables are automatically initialized to zero.
  • Since global variables can be accessed by any part of the program, this means they can potentially be changed from any part of the program. This can make finding errors and debugging more difficult.

Top comments (0)