Variables and Operators

Where Do We Store Values?

Variables give us a way to associate a logical name with a value. Creating variables has two key parts:

  1. Declaration

    • Where we tell our compiler the type of our value, and the name we want to use

  2. Initialization

    • Where we decide the initial value of our variable

All variables must be declared before they can be used. For example, we can declare a new integer (positive or negative whole number) that will hold someone’s age with int age;. This tells our compiler that we want an integer, and we are going to refer to the integer with the name age.

We can initialize a variable using the = operator. For example, we can set the initial value of age to 28 with the statement age = 28;.

While we can declare and initialize variables separately, it is good practice to do both in a single statement. This helps prevent the accidental use of uninitialized variables. For example, we can do the declaration and initialization of our variable age with the statement int age = 28;

Relevant Links

Automatic Type Deduction

One of the convenient parts of modern C++ is automatic type deduction. This is where we allow our compiler to deduce the type of a value instead of manually specifying it.

There are a number of reasons why we use this feature:

  • It prevents uninitialized variables

  • It’s convenient (some types have incredibly long names)

  • It’s necessary in some cases (some types are known only to the compiler)

The keyword we use for automatic type deduction is auto. For example, instead of writing int age = 28;, we could write auto age = 28. This works because the compiler knows that 28 is an integer, so it can deduce that age should be that same type.

However, we can not write auto age;. Our compiler does not have enough information to deduce what type age should be from this statement.

Relevant Links

How Do We Use Values?

Values (immediate ones like 28, or variables like age) are used with operators to perform useful work. Operators are how we specify computations with values. There are a number of different types of operators in C++, including:

  • Arithmetic Operators

    • +, -, *, /, etc.

  • Comparison Operators

    • ==, <, >, etc.

  • Logical Operators

    • !, ||, &&

There are additional operators for accessing data, performing actions like function calls, and combined operators for arithmetic and assignment.

When using familiar types like float and int, the operations are fairly intuitive. We can add two numbers together with +, multiply them with *, and check if one is greater than another with >. There operators work with both values stored using variables, or immediate values.

In later posts, we’ll see how more complex types implement their own custom versions of operators (e.g., how we can combine/concatenate two std::string with the + operator.

Relevant Links

Previous
Previous

Introduction

Next
Next

Printing with the Standard Library