Variables and Constants

Variables

A variable in C++ is a named storage location in the computer’s memory that holds a value that can be changed during program execution. Think of variables as labeled containers for storing data.

Declaring Variables

In C++, you must declare a variable before using it. The basic syntax for variable declaration is:

data_type variable_name;

For example:

int age;           // Declares an integer variable named 'age'
double salary;     // Declares a double-precision floating-point variable named 'salary'
char grade;        // Declares a character variable named 'grade'
bool isEmployed;   // Declares a boolean variable named 'isEmployed'

Initializing Variables

You can initialize a variable (assign an initial value) at the time of declaration:

int age = 25;              // Initializes age to 25
double salary = 50000.50;  // Initializes salary to 50000.50
char grade = 'A';          // Initializes grade to 'A'
bool isEmployed = true;    // Initializes isEmployed to true

C++ provides different ways to initialize variables:

1. Copy Initialization

int count = 10;

2. Direct Initialization

int count(10);

3. Uniform/Brace Initialization (C++11)

int count{10};  // Preferred in modern C++
int count = {10};

Brace initialization prevents narrowing conversions (conversions that might lose data):

int x = 3.14;    // Allowed, but data loss occurs (x becomes 3)
int y{3.14};     // Error: narrowing conversion not allowed

Multiple Variable Declaration

You can declare multiple variables of the same type in a single statement:

int x, y, z;           // Declares three integer variables
int a = 5, b = 10;     // Declares and initializes two integer variables

Variable Scope

The scope of a variable determines its visibility and lifetime in a program.

1. Local Variables

Local variables are defined inside a function or block and can only be accessed within that function or block:

void exampleFunction() {
    int localVar = 10;  // Local variable
    // localVar is accessible only within this function
}

int main() {
    // localVar is not accessible here
    return 0;
}

2. Global Variables

Global variables are defined outside of all functions and can be accessed throughout the program:

int globalVar = 100;  // Global variable

void exampleFunction() {
    // globalVar is accessible here
    globalVar = 200;
}

int main() {
    // globalVar is also accessible here
    return 0;
}

3. Block Scope

Variables defined within a block (enclosed by curly braces) are only accessible within that block:

int main() {
    {
        int blockVar = 50;  // Block-scoped variable
        // blockVar is accessible here
    }
    // blockVar is not accessible here
    return 0;
}

Variable Naming Conventions

While naming variables:

  1. Use descriptive names that indicate the purpose of the variable
  2. Follow consistent naming conventions (camelCase, snake_case, etc.)
  3. Avoid using reserved keywords
  4. Start with a letter or underscore, not a digit
  5. Use only letters, digits, and underscores

Variable Type Modifiers

C++ provides several type modifiers that can be applied to basic data types:

1. Size Modifiers

  • short: Typically reduces the size of an integer
  • long: Typically increases the size of an integer
  • long long: (C++11) Provides even larger integer type
short int smallNumber = 10;
long int largeNumber = 1000000;
long long int veryLargeNumber = 10000000000LL;

2. Sign Modifiers

  • signed: Variable can hold both positive and negative values (default for most types)
  • unsigned: Variable can hold only non-negative values
unsigned int positiveOnly = 100;
signed int canBeNegative = -100;

Type Inference with auto (C++11)

The auto keyword allows the compiler to automatically deduce the type of a variable from its initializer:

auto x = 10;        // x is deduced to be an int
auto y = 3.14;      // y is deduced to be a double
auto z = 'c';       // z is deduced to be a char
auto name = "John"; // name is deduced to be const char*

Memory Aspects of Variables

Every variable occupies memory space depending on its data type:

#include <iostream>
using namespace std;

int main() {
    cout << "Size of int: " << sizeof(int) << " bytes" << endl;
    cout << "Size of char: " << sizeof(char) << " byte" << endl;
    cout << "Size of float: " << sizeof(float) << " bytes" << endl;
    cout << "Size of double: " << sizeof(double) << " bytes" << endl;
    cout << "Size of bool: " << sizeof(bool) << " byte" << endl;
    return 0;
}

Type Casting

Type casting is the process of converting a variable from one data type to another.

1. Implicit Type Casting (Automatic)

int x = 10;
double y = x;  // Implicit conversion from int to double

2. Explicit Type Casting

C-style casting

double x = 3.14;
int y = (int)x;  // Explicitly convert double to int

C++ style casting

double x = 3.14;
int y = static_cast<int>(x);  // Modern C++ way to cast

Constants

A constant is a variable whose value cannot be changed after initialization. Constants are useful for values that should remain fixed throughout the program.

Types of Constants in C++

1. Literal Constants

These are fixed values directly written into the code:

10          // Integer literal
3.14        // Floating-point literal
'A'         // Character literal
"Hello"     // String literal
true        // Boolean literal
nullptr     // Pointer literal (C++11)

2. Declared Constants

Using const Keyword

The most common way to define constants in modern C++:

const int MAX_STUDENTS = 50;
const double PI = 3.14159;
const char GRADE_A = 'A';
const std::string WELCOME_MESSAGE = "Welcome to C++";

Best practices for declared constants:

  • Use ALL_CAPS naming convention with underscores for constants
  • Initialize constants at the time of declaration

Using constexpr Keyword (C++11)

For constants that can be evaluated at compile time:

constexpr int ARRAY_SIZE = 100;
constexpr double SPEED_OF_LIGHT = 299792458.0;  // meters per second

3. Enumeration Constants

Enumerations allow you to create a set of named integer constants:

enum Color {RED, GREEN, BLUE};  // RED=0, GREEN=1, BLUE=2

enum Weekday {MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};
// MONDAY=1, TUESDAY=2, ...

With C++11, you can use scoped enumerations (enum class) to avoid name conflicts:

enum class Status {PENDING, APPROVED, REJECTED};

Status current = Status::APPROVED;  // Must use scope resolution operator

4. Defined Constants (using #define)

This is a preprocessor directive (replaced by the preprocessor before compilation):

#define PI 3.14159
#define MAX_BUFFER_SIZE 1024

Note: Using #define for constants is not recommended in modern C++ because:

  • No type checking
  • No scope rules
  • Can lead to unexpected behavior due to text substitution
  • Cannot be debugged as easily

const vs #define

Featureconst#define
Type safetyYesNo
Memory allocationYesNo (text substitution)
Scope rulesYesNo (global by default)
DebuggingEasyDifficult
Recommended in modern C++YesNo

Constants in Functions and Classes

Constant Parameters

void display(const int value) {
    // value cannot be modified in this function
    // value = 10;  // Error: assignment of read-only parameter
    std::cout << value << std::endl;
}

Constant Member Functions

class Rectangle {
private:
    int width, height;
    
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    
    int getArea() const {  // This function cannot modify class members
        return width * height;
        // width = 10;  // Error: cannot modify in const function
    }
};

Constant Objects

const Rectangle rect(5, 3);
int area = rect.getArea();  // OK: getArea() is const
// rect.setWidth(10);  // Error: cannot call non-const method on const object

Practical Examples

Example 1: Using Variables and Constants Together

#include <iostream>
using namespace std;

const double PI = 3.14159;

int main() {
    double radius;
    cout << "Enter the radius of the circle: ";
    cin >> radius;
    
    double area = PI * radius * radius;
    double circumference = 2 * PI * radius;
    
    cout << "Area: " << area << endl;
    cout << "Circumference: " << circumference << endl;
    
    return 0;
}

Example 2: Temperature Conversion Program

#include <iostream>
using namespace std;

int main() {
    const double FREEZING_POINT = 32.0;
    const double CONVERSION_FACTOR = 5.0/9.0;
    
    double fahrenheit;
    cout << "Enter temperature in Fahrenheit: ";
    cin >> fahrenheit;
    
    double celsius = (fahrenheit - FREEZING_POINT) * CONVERSION_FACTOR;
    
    cout << fahrenheit << " degrees Fahrenheit = ";
    cout << celsius << " degrees Celsius" << endl;
    
    return 0;
}

Best Practices

  1. Initialize variables: Always initialize variables when declaring them
  2. Use constants for fixed values: If a value shouldn’t change, make it a constant
  3. Use meaningful names: Choose descriptive names for variables and constants
  4. Prefer const over #define: Use const for constants in modern C++
  5. Use appropriate data types: Choose the most appropriate data type for your variables
  6. Limit scope: Declare variables in the smallest necessary scope
  7. Use const correctly: Apply const to variables, parameters, and member functions when appropriate
  8. Consider using constexpr: For values that can be computed at compile time

By properly understanding and using variables and constants in C++, you can write more maintainable, readable, and error-free code.