Skip to content

Module 2 · Variables, Operators and Control Flow — topic 1 of 4

Variables and Data Types

Fundamental types, bool, std::string, the auto keyword, const and constexpr, and the brace initialisation that prevents narrowing conversions.

Beginner 15 min read·Lesson 4 of 40 in C++ Programming

Learning objectives

  • Declare variables using several initialisation styles
  • Use auto, const and constexpr appropriately
  • Explain how brace initialisation prevents narrowing

Definition

A variable is a named object of a specific type. C++ provides fundamental types (bool, char, int, long long, float, double…), library types such as std::string, and lets the compiler deduce a type with auto.

Introduction

C++ keeps C's numeric types and adds a real bool type with the literals true and false, plus library types like std::string that behave like built-in values.

C++11 introduced auto, which deduces a variable's type from its initialiser, and brace initialisation int x{5};, which works uniformly for every type and rejects accidental data loss.

Why it matters

Choosing the right type and initialising every variable removes many bugs at compile time.

const and constexpr let the compiler enforce that values do not change and even compute them at compile time.

Detailed explanation

Initialisation styles: int a = 5; (copy), int b(5); (direct), int c{5}; (brace / list). Brace initialisation is preferred because int d{3.7}; is a compile error — the double would be narrowed — whereas int d = 3.7; silently truncates.

auto x = 3.0; makes x a double; auto s = std::string("hi"); a std::string. auto still gives a static type — it is decided at compile time.

const int max = 100; cannot change after initialisation. constexpr int size = 10 * 4; must be computable at compile time and can be used where constants are required, such as array sizes.

TypeTypical sizeExample
bool1 bytetrue
char1 byte'A'
int4 bytes42
long long8 bytes9000000000LL
double8 bytes3.14
std::stringvaries"hello"

Syntax

C++
int count{0};
double price = 49.5;
bool done = false;
auto total = count * price; // double
const std::string name{"Asha"};
constexpr int kMax = 64;
  • Use {} for most initialisation.
  • auto requires an initialiser.
  • constexpr implies const.

Code examples

Types and sizes

C++
#include <iostream>
int main() {
bool ok{true};
char grade{'A'};
int marks{92};
double cgpa{8.75};
std::cout << std::boolalpha << ok << ' ' << grade << ' ' << marks << ' ' << cgpa << '\n';
std::cout << sizeof(bool) << ' ' << sizeof(int) << ' ' << sizeof(double) << '\n';
return 0;
}
Output
true A 92 8.75
1 4 8

std::boolalpha prints booleans as words instead of 1/0.

auto deduces the type

C++
#include <iostream>
#include <string>
int main() {
auto n = 7; // int
auto x = n / 2.0; // double
auto s = std::string("C++");
std::cout << n << ' ' << x << ' ' << s.size() << '\n';
return 0;
}
Output
7 3.5 3

More examples

constexpr and narrowing

C++
#include <iostream>
constexpr int square(int v) { return v * v; }
int main() {
constexpr int side = 6;
constexpr int area = square(side); // computed at compile time
int grid[area]; // allowed: area is a constant expression
double avg = 7.9;
int truncated = static_cast<int>(avg); // explicit, visible conversion
// int bad{avg}; // error: narrowing conversion from double to int
std::cout << area << ' ' << sizeof grid / sizeof grid[0] << ' ' << truncated << '\n';
return 0;
}
Output
36 36 7

Step-by-step explanation

  • constexpr int square(int) can run at compile time when its argument is constant.
  • area is 36 and is known before the program runs, so it can size an array.
  • static_cast<int>(avg) makes the truncation explicit.
  • The commented line would not compile: braces forbid narrowing.

Expected output

Running “constexpr and narrowing” prints exactly:

TextOutput
36 36 7

Practical applications

  • Embedded C++ uses constexpr tables computed at compile time to save run-time work.
  • Game code uses auto for long iterator and lambda types.
  • Libraries mark configuration values constexpr so they cost nothing at run time.

Best practices

  • Initialise every variable, preferably with braces.
  • Use auto when the type is obvious from the right-hand side or very long.
  • Use const by default and drop it only when the value must change.

Common mistakes

Silent truncation with =

Avoid

int marks = 89.6;

Prefer

int marks{static_cast<int>(89.6)};

Copy-initialisation silently drops .6; braces would refuse, forcing you to make the conversion explicit.

auto with braces in C++11

Avoid

auto n = {5}; // std::initializer_list<int>

Prefer

auto n = 5; // int

auto x = {5}; deduces an initializer_list, not an int.

Important notes

  • Signed integer overflow is undefined behaviour in C++ just as in C.
  • std::string is not a fundamental type but behaves like a value: copying it copies the characters.

Key takeaways

  • Brace initialisation prevents narrowing.
  • auto deduces a static type from the initialiser.
  • constexpr values are computed at compile time.

Try it yourself

  1. 1
    Declare variables of five different types using brace initialisation and print them.
  2. 2
    Write a constexpr function cube and use it to size an array.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is the result of compiling `int x{3.7};`?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic