FirstHack Learn
Log in Sign up free

Variables, Types and Input/Output

9 min read · 20 views

Variables, Types and Input/Output

A variable is a named piece of memory. In C++ every variable has a type, fixed at the moment you declare it and never changing afterwards. The type tells the compiler three things: how many bytes to set aside, how to interpret those bytes, and which operations are legal.

This is different from Python, where a name can hold an integer now and a string later. C++ decides types at compile time. That is why C++ catches a whole class of mistakes before your program ever runs, and why you have to be specific up front.

The built-in types

Type Typical size Holds Example
int 4 bytes Whole numbers, roughly ±2 billion int age = 19;
long long 8 bytes Much larger whole numbers long long pop = 1400000000LL;
float 4 bytes Decimals, about 7 digits of precision float g = 9.8f;
double 8 bytes Decimals, about 15 digits double pi = 3.14159;
char 1 byte A single character char grade = 'A';
bool 1 byte true or false bool passed = true;
std::string varies Text of any length std::string s = "hello";

Two notes on that table. First, the sizes are typical, not guaranteed; the standard only sets minimums. Second, bool is a real type in C++, unlike C where you needed stdbool.h or an int. Use it. A function that returns bool documents itself.

Prefer double over float unless you have a specific reason. On modern hardware double is not meaningfully slower, and the extra precision saves you from surprises.

Declaring and initialising

C++
#include <iostream>
#include <string>

int main() {
    int rollNumber = 42;
    double cgpa = 8.65;
    char section = 'B';
    bool hostelResident = false;
    std::string name = "Ravi Kumar";

    std::cout << "Name: " << name << "\n";
    std::cout << "Roll: " << rollNumber << ", Section: " << section << "\n";
    std::cout << "CGPA: " << cgpa << "\n";
    std::cout << "Hostel: " << hostelResident << "\n";
    std::cout << "Hostel (words): " << std::boolalpha << hostelResident << "\n";

    return 0;
}

By default a bool prints as 1 or 0. The std::boolalpha manipulator switches the stream to printing true and false instead, and it stays switched until you change it back.

Always initialise. A local variable declared as int x; with no value does not contain zero. It contains whatever bytes were already at that address, which could be anything. Reading it is undefined behaviour, and the symptom is a program that works on your laptop and fails in the lab.

The auto keyword

Since C++11 you can write auto and let the compiler work out the type from the initialiser.

C++
#include <iostream>
#include <string>

int main() {
    auto count = 10;             // int
    auto ratio = 2.5;            // double
    auto letter = 'x';           // char
    auto title = std::string("Data Structures");

    std::cout << count << " " << ratio << " " << letter << "\n";
    std::cout << title << " has " << title.size() << " characters\n";

    return 0;
}

auto is not dynamic typing. The type is still decided at compile time and still fixed forever; you have only saved yourself from writing it out. That makes it genuinely useful for long type names, which you will meet when you start using iterators.

For simple cases, spelling out int is clearer than auto. One trap worth knowing now: auto s = "hello"; does not give you a std::string. It gives a const char*, the old C-style string pointer, because that is what a bare quoted literal is. Write std::string s = "hello"; when you want a string.

Constants

Use const for a value that must not change after initialisation.

Writing const double PI = 3.14159; means the compiler rejects any attempt to assign to PI. This is not merely a comment to future readers. It is a checked promise, and it catches real bugs.

Output with cout

std::cout is an object representing standard output, and << sends data to it. You can chain any number of insertions, mixing types freely, because the compiler picks the correct handling for each one.

To control decimal places, include <iomanip> and use std::fixed with std::setprecision.

C++
#include <iostream>
#include <iomanip>

int main() {
    double total = 456.0;
    double count = 7.0;
    double average = total / count;

    std::cout << "Raw:      " << average << "\n";
    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Rounded:  " << average << "\n";
    std::cout << "Also:     " << (total / 2) << "\n";

    return 0;
}

Both manipulators are sticky: once set, they apply to everything printed afterwards on that stream, which is why the last line also shows two decimals.

Input with cin

Reading input uses std::cin and the extraction operator >>. The arrows point the other way, away from the stream and into your variable.

TEXT
#include <iostream>
#include <string>

int main() {
    int age;
    std::string name;

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Enter your name: ";
    std::cin >> name;

    std::cout << name << " is " << age << " years old\n";
    return 0;
}

There is one behaviour that catches everyone. std::cin >> name stops at the first whitespace. If you type Ravi Kumar, name receives only Ravi, and Kumar stays in the buffer waiting to confuse your next read. To read a whole line including spaces, use std::getline(std::cin, name) instead.

Mixing the two makes it worse. After std::cin >> age, the newline you pressed is still sitting in the buffer, so an immediately following getline reads that leftover newline and returns an empty string. The fix is to discard the rest of the line first:

TEXT
std::cin >> age;
std::cin.ignore(10000, '\n');
std::getline(std::cin, name);
⚠️endl versus backslash-n

std::endl writes a newline and flushes the output buffer, forcing the operating system to write immediately. "\n" writes only the newline and lets the buffer fill up naturally. Flushing on every line is slow. Inside a loop that prints thousands of lines, endl can make your program noticeably slower for no benefit. Use "\n" by default and keep endl for the rare case where you need output to appear right now.

Common mistakes

  • Using a variable before initialising it. int sum; sum += 5; adds to garbage. Write int sum = 0;.
  • Using >> with cin for names with spaces. It stops at the space. Use std::getline.
  • Calling getline right after cin >>. The leftover newline is consumed and you get an empty string. Call std::cin.ignore(10000, '\n'); in between.
  • Integer division where you wanted a decimal. sum / count with two ints truncates. Make one a double, for example sum / (double)count.
  • Assuming auto s = "text"; gives a std::string. It gives const char*, so s.size() will not compile. Name the type.
  • Confusing = and ==. if (x = 5) assigns 5 and is always true. Comparison is ==. Turn on -Wall and the compiler warns you.

Types and I/O are the plumbing of every program you will write. Once they feel automatic, control flow becomes much easier. Try a few input-and-calculate exercises on the Practice page.

Create a free account to track what you have finished.