SrcForge

Lesson 6

Variables and Constants

Covers variables, constants, naming rules, best practices.

Lesson content

What are variables and constants?

Variables store data. Value can change.

Constants hold fixed values. Value stays same.

Variable is a whiteboard. Constant is stone.

Why do we need variables and constants?

  • Store information for later use
  • Perform calculations
  • Accept input from users
  • Improve code readability
  • Prevent accidental modification of fixed values

Variables and constants overview

                  Variables & Constants

          ┌───────────────┴───────────────┐
          │                               │
          ▼                               ▼
      Variables                      Constants
          │                               │
   Value Can Change              Value Cannot Change
          │                               │
          ▼                               ▼
    int age = 20;          const float PI = 3.14159;

Variables in C++

What is a variable?

Named memory spot. Holds data that can change.

Variable declaration

data_type variable_name;

int age;

Variable initialization

Initialization sets a value at declaration.

int age = 20;

Variable naming rules

  • Letters, digits, underscores allowed
  • Must start with letter or underscore
  • Names are case-sensitive
  • No spaces allowed
  • No reserved keywords allowed
// Valid
age
studentName
_marks
totalScore
number1

// Invalid
1age          // Starts with a digit
student name  // Contains a space
float         // Reserved keyword
total-score   // Contains a hyphen

Example 1: Declaring variables

#include <iostream>
using namespace std;

int main()
{
    int age = 20;
    float salary = 55000.50f;
    char grade = 'A';
    bool isStudent = true;

    cout << "Age: " << age << endl;
    cout << "Salary: " << salary << endl;
    cout << "Grade: " << grade << endl;
    cout << "Student: " << isStudent << endl;

    return 0;
}

Modifying a variable

Variable value can change anytime.

#include <iostream>
using namespace std;

int main()
{
    int score = 50;
    score = 80;
    cout << score << endl;
    return 0;
}

Constants in C++

What is a constant?

Value stays fixed throughout the program.

  • Pi (π)
  • Speed of light
  • Tax rates
  • Maximum number of users
  • Days in a week

Using the const keyword

const keyword creates a constant value.

const double PI = 3.141592653589793;

Example 2: Using constants

#include <iostream>
using namespace std;

int main()
{
    const double PI = 3.14159;
    double radius = 5.0;
    double area = PI * radius * radius;

    cout << "Area = " << area << endl;

    return 0;
}

Example 3: Variable vs constant

#include <iostream>
using namespace std;

int main()
{
    int marks = 80;
    const int passingMarks = 40;

    marks = 90;  // Allowed

    // passingMarks = 50;  // Error

    cout << "Marks: " << marks << endl;
    cout << "Passing Marks: " << passingMarks << endl;

    return 0;
}

Variables vs constants

Feature      | Variable             | Constant
------------ | -------------------- | --------------------
Value        | Can change           | Cannot change
Keyword      | No special keyword   | const
Memory       | Allocated at runtime | Allocated at runtime
Modification | Allowed              | Not allowed
Example      | int age = 20;        | const int DAYS = 7;

Common mistakes and pitfalls

  • Uninitialized variable. Fix: initialize before use
  • Modifying a constant. Fix: keep value fixed
  • Reserved keyword as name. Fix: pick valid names
  • Unclear names like a or x1. Fix: use descriptive names
// Incorrect
const int MAX = 100;
MAX = 200;
// Correct
const int MAX = 100;
cout << MAX;

Best practices

  • Use descriptive variable names
  • Initialize variables when declaring
  • Use const for fixed values
  • Follow consistent naming convention
  • Avoid unnecessary global variables
  • Prefer const over magic numbers

When not to use variables or constants

  • Variable for fixed value. Use a constant
  • Repeated hard-coded values. Use named constant
  • Unneeded global variables. Use local scope

Summary

  • Variable holds changeable data
  • Constant holds fixed data
  • Initialize variables before use
  • Use meaningful names always
  • Use const for fixed values
  • Good naming aids maintenance

Frequently asked questions

What is the difference between a variable and a constant?

Variable changes. Constant stays fixed after init.

Why should I use const instead of a regular variable?

Prevents accidental changes. Keeps code safer.

Can I declare a variable without assigning a value?

Yes. But initialize before use to avoid bugs.

What are the rules for naming variables?

Start with letter or underscore. No spaces or keywords.

What is a literal in C++?

Fixed value written directly in code, like 10 or 'A'.

What should I learn after variables and constants?

  • Literals
  • Operators
  • User Input (cin)
  • Type Casting
  • Expressions
  • Control Statements (if, switch)
  • Loops (for, while, do-while)