C++ Variables

Declaring Variables

C++ requires you to declare a variable with its type before using it:

int age = 30;
float price = 19.99;
char grade = 'A';
bool isActive = true;

Use string for text (requires #include <string>).

Multiple Declarations

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

int x = 5, y = 10, z = 0;

Initialization

Always initialize variables to avoid undefined values:

int number;      // might contain garbage
number = 42;     // assigned later

int count = 0;   // preferred

Variable Scope

Variables are accessible only within the block they are defined in:

void example() {
    int local = 10;
    cout << local;
}
// local is not accessible here

Global variables are declared outside any function.

Constants

Use const to declare constants:

const double PI = 3.14159;

Constants cannot be reassigned after initialization.

Best Practices

  • Use meaningful names (e.g., studentAge)
  • Initialize variables when declared
  • Avoid global variables unless necessary

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic