2.2) Variables and constants in C++

Variables and constants are fundamental concepts in programming that allow you to store and manipulate data.

Let’s explore these concepts in C++ with code examples and explanations.

Variables in C++

A variable is a named memory location that can hold a value. You can change the value stored in a variable during program execution.

#include <iostream>
using namespace std;

int main() {
    int age; // Declare a variable
    age = 25; // Assign a value
    cout << "Age: " << age << endl;

    double pi = 3.14159; // Declare and initialize
    cout << "Pi: " << pi << endl;

    return 0;
}

Output:

Age: 25
Pi: 3.14159

Explanation:

  • A variable is declared using a data type followed by its name (e.g., int age;).
  • The = operator assigns a value to a variable (e.g., age = 25;).
  • You can also declare and initialize a variable in a single step (e.g., double pi = 3.14159;).
  • cout is used to output variable values.

Constants in C++

A constant is a value that cannot be changed after it’s assigned. It’s useful for defining values that should remain constant throughout the program.

#include <iostream>
using namespace std;

int main() {
    const int gravity = 9.81; // Declare a constant
    // gravity = 9.8; // Error: Cannot modify a constant
    cout << "Gravity: " << gravity << " m/s^2" << endl;

    const double pi = 3.14159;
    cout << "Pi: " << pi << endl;

    return 0;
}

Output:

Gravity: 9.81 m/s^2
Pi: 3.14159

Explanation:

  • A constant is declared using the const keyword followed by the data type and its name (e.g., const int gravity;).
  • Constants must be initialized when declared, and their values cannot be changed afterward.
  • Attempting to modify a constant will result in a compilation error.

Global vs. Local Variables

Variables can have global or local scope:

#include <iostream>
using namespace std;

int globalVar = 10; // Global variable

int main() {
    int localVar = 5; // Local variable
    cout << "Global variable: " << globalVar << endl;
    cout << "Local variable: " << localVar << endl;
    return 0;
}

Output:

Global variable: 10
Local variable: 5

Explanation:

  • Global variables are declared outside functions and can be accessed from any part of the program.
  • Local variables are declared within functions and are limited to their scope.

Understanding variables and constants is crucial for managing data and controlling the flow of your C++ programs.

Additional points

let’s delve deeper into variables and constants in C++ by exploring some additional points:

1. Variable Naming Conventions

Follow naming conventions for variables to enhance code readability:

  • Use descriptive names (e.g., age instead of a).
  • Start variable names with a letter or underscore.
  • Avoid reserved keywords (e.g., int, double) as variable names.
  • Use camelCase or snake_case for multi-word variable names.

2. Initializing Variables

Variables should be initialized before using them to avoid accessing undefined values:

int x; // Not initialized
int y = 10; // Initialized

3. Constants and constexpr

The constexpr keyword is used to declare constants that are computed at compile time:

constexpr int daysInWeek = 7;

4. Data Type Modifiers

Modifiers like unsigned, signed, and long can be used with data types to adjust their range:

unsigned int positiveNumber = 42; // Only positive values
long long largeNumber = 123456789012345;

5. Scope of Variables

Local variables are defined within a block or function and have limited scope:

int main() {
    int localVar = 5; // Local variable
    // localVar is only accessible within main()
}

6. Shadowing Variables

Avoid reusing variable names within nested scopes, as it can lead to confusion:

int x = 10;

void myFunction() {
    int x = 20; // Shadows the global x
    // Use x within this function
}

7. Global Constants

Declare global constants using the const keyword outside of functions:

const double pi = 3.14159;

8. Literal Constants

A literal constant is a fixed value directly written in the code (e.g., 5, 3.14, 'A').

9. Enumerated Constants

Enumerations (enum) define a set of named integer constants:

enum Color { RED, GREEN, BLUE };
Color myColor = GREEN;

10. #define Preprocessor Directive

The #define directive defines constants using macros:

#define PI 3.14159

11. Global Variables and Initialization Order

Global variables are initialized before the main() function runs. Be cautious with dependencies on the order of initialization.

int globalVar = 10; // Initialized before main()

int main() {
    cout << "Global variable: " << globalVar << endl;
    return 0;
}