0
0
CppHow-ToBeginner · 3 min read

How to Declare Variables in C++: Syntax and Examples

In C++, you declare a variable by specifying its type followed by its name. For example, int age; declares an integer variable named age. You can also initialize it during declaration like int age = 25;.
📐

Syntax

To declare a variable in C++, you write the type of the variable first, then the variable name. Optionally, you can assign an initial value using the = sign.

  • type: The kind of data the variable will hold (e.g., int, double, char).
  • variable name: The name you choose to identify the variable.
  • initial value (optional): The value assigned to the variable when it is created.
cpp
type variable_name;
type variable_name = initial_value;
💻

Example

This example shows how to declare variables of different types and initialize them. It also prints their values to the screen.

cpp
#include <iostream>

int main() {
    int age = 30;           // integer variable
    double height = 1.75;   // floating-point variable
    char grade = 'A';       // character variable

    std::cout << "Age: " << age << std::endl;
    std::cout << "Height: " << height << std::endl;
    std::cout << "Grade: " << grade << std::endl;

    return 0;
}
Output
Age: 30 Height: 1.75 Grade: A
⚠️

Common Pitfalls

Some common mistakes when declaring variables in C++ include:

  • Forgetting to specify the type before the variable name.
  • Using invalid variable names (like starting with a number or using spaces).
  • Declaring a variable without initializing it and then using it before assigning a value.
  • Confusing the assignment operator = with the equality operator ==.

Here is an example showing wrong and right ways:

cpp
// Wrong: missing type
// age = 25;

// Wrong: invalid variable name
// int 2age;

// Wrong: using uninitialized variable
// int score;
// std::cout << score; // undefined behavior

// Right: correct declaration and initialization
int age = 25;
int score = 0;
std::cout << score;
Output
0
📊

Quick Reference

Here is a quick summary of common C++ variable types and examples of declarations:

TypeDescriptionExample Declaration
intWhole numbersint count;
doubleDecimal numbersdouble price = 9.99;
charSingle characterchar letter = 'B';
boolTrue or falsebool isOpen = true;
stringText (needs #include )std::string name = "Alice";

Key Takeaways

Always specify the variable type before the variable name in C++.
You can declare and initialize a variable in one line for clarity.
Avoid using uninitialized variables to prevent unpredictable behavior.
Variable names must start with a letter or underscore and contain no spaces.
Use appropriate types to match the kind of data you want to store.