CodeToLive

Variables and Data Types in C++

In C++, variables are used to store data values. C++ is a statically typed language, meaning you must declare the type of a variable before using it. Variables are essential for storing and manipulating data in programs.

Declaring Variables

Variables in C++ are declared using the syntax: type variable_name;. You can also initialize a variable at the time of declaration.


int age = 25;  // Integer
double height = 5.9;  // Double
std::string name = "Alice";  // String
bool isStudent = true;  // Boolean
      

Common Data Types

C++ provides several built-in data types to represent different kinds of data:

Type Modifiers

Type modifiers like signed, unsigned, short, and long can be used to alter the range and behavior of data types.


unsigned int positiveNumber = 100;  // Only positive values
short int smallNumber = 32767;  // Smaller range
long int largeNumber = 2147483647;  // Larger range
      

Constants

Constants are fixed values that cannot be changed during program execution. They are declared using the const keyword.


const double PI = 3.14159;  // Constant value
      

Variable Scope

The scope of a variable determines where it can be accessed in a program. Variables can have:


#include <iostream>

int globalVar = 10;  // Global variable

void function() {
    int localVar = 20;  // Local variable
    std::cout << "Local Variable: " << localVar << std::endl;
}

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

Example: Using Variables and Data Types


#include <iostream>
#include <string>

int main() {
    int age = 25;
    double height = 5.9;
    std::string name = "Alice";
    bool isStudent = true;
    const double PI = 3.14159;

    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Height: " << height << std::endl;
    std::cout << "Is Student: " << isStudent << std::endl;
    std::cout << "Value of PI: " << PI << std::endl;

    return 0;
}
      

Best Practices

Next: Control Structures