LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 1 of 27

Basic Syntax and Data Types

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Basic Syntax and Data Types · Study material

C++ basic syntax and data types are the first things every C++ interview and exam tests: how a program is structured, what #include <iostream> and std:: mean, how big an int is, why int x{3.5}; does not compile, and what 7 / 2 prints. This page explains the essentials of modern C++ – from main() and namespaces to auto, constexpr, brace initialization and C++23 std::print – with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – whose answers were checked on a real C++ compiler.

On this page

  • Structure of a C++ program: headers, main(), statements, comments
  • Fundamental data types, their sizes and ranges
  • Variables and initialization: =, (), {}, auto, const, constexpr
  • Type conversions, static_cast, namespaces and modern formatted output

Structure of a C++ program

Lines starting with # are preprocessor directives: #include <iostream> makes the standard input/output library available. Execution starts in int main(). Statements end with a semicolon, blocks are enclosed in braces, and comments are written with // (to the end of the line) or /* … */. Reaching the end of main returns 0 automatically.

#include <iostream>     // preprocessor: brings in std::cout and std::cin

// Every C++ program starts running in main()
int main() {
    std::cout << "Hello, LearnFrenzy!" << '\n';   // << sends values to the output stream
    std::cout << "C++ " << 20 << " is ready" << '\n';
    return 0;                                     // 0 = success (optional in main)
}

Output

Hello, LearnFrenzy!
C++ 20 is ready

'\n' ends a line; std::endl also ends the line but additionally flushes the output buffer, which is slower inside loops.

How a C++ program is built

A C++ source file goes through four stages before it runs. Knowing them explains most error messages: a missing semicolon is a compile error, while a function that is declared but never defined is a link error.

  1. Preprocessing – #include files are pasted in, macros are expanded.
  2. Compilation – the code is checked and translated into assembly / machine code.
  3. Assembly – an object file (.o / .obj) is produced.
  4. Linking – object files and libraries are combined into an executable.
# GCC or Clang: compile and link in one step, with warnings, as C++20
g++ -std=c++20 -Wall -Wextra main.cpp -o main
./main

# The stages one by one
g++ -E main.cpp -o main.ii      # 1. preprocess only
g++ -S main.ii -o main.s        # 2. compile to assembly
g++ -c main.s  -o main.o        # 3. assemble to an object file
g++ main.o -o main              # 4. link

Comments, keywords and identifiers

C++ has about 90 keywords (int, class, return, new, delete, template, constexpr …) that cannot be used as names. An identifier may contain letters, digits and underscores, must not start with a digit, and is case-sensitive: total and Total are different variables. Names beginning with an underscore and a capital letter, or containing a double underscore, are reserved for the compiler and library.

EscapeMeaningEscapeMeaning
\nnewline\\backslash
\thorizontal tab\" / \'double / single quote
\0null character\x41character by hex code ('A')
#include <iostream>

int main() {
    std::cout << "Name:\tAsha\n";                 // \t tab, \n newline
    std::cout << "Path: C:\\code\\main.cpp\n";    // \\ backslash
    std::cout << "She said \"hi\" and 'bye'\n";   // \" double quote
    std::cout << R"(Raw: C:\code\n "as is")" << '\n';   // raw string literal: no escapes
    return 0;
}

Output

Name:	Asha
Path: C:\code\main.cpp
She said "hi" and 'bye'
Raw: C:\code\n "as is"

Fundamental data types

C++ guarantees minimum sizes, not exact ones – but on every mainstream 64-bit compiler the sizes below are what you get. sizeof(char) is always 1.

TypeTypical sizeHolds
bool1 bytetrue / false
char1 byteone character / small integer
short2 bytes−32,768 to 32,767
int4 bytesabout ±2.1 billion
long long8 bytesabout ±9.2 × 1018
float4 bytes~6–7 significant digits
double8 bytes~15–16 significant digits
#include <iostream>
#include <limits>

int main() {
    std::cout << "char "      << sizeof(char)      << ", bool " << sizeof(bool)
              << ", short "   << sizeof(short)     << ", int "  << sizeof(int)
              << ", long long " << sizeof(long long) << '\n';
    std::cout << "float "     << sizeof(float)     << ", double " << sizeof(double) << '\n';
    std::cout << "int range: " << std::numeric_limits<int>::min() << " to "
              << std::numeric_limits<int>::max() << '\n';
    std::cout << "float digits: " << std::numeric_limits<float>::digits10
              << ", double digits: " << std::numeric_limits<double>::digits10 << '\n';
    return 0;
}

Output

char 1, bool 1, short 2, int 4, long long 8
float 4, double 8
int range: -2147483648 to 2147483647
float digits: 6, double digits: 15

Unsigned variants (unsigned int …) hold only non-negative values and wrap around on overflow; signed overflow is undefined behaviour. For exact widths use std::int32_t, std::int64_t from <cstdint>.

Variables and initialization

C++ has several ways to initialize a variable. Brace initialization int c{30}; works everywhere and refuses narrowing conversions such as double → int, which is why modern style prefers it. auto deduces the type from the initializer, const makes a variable read-only, and constexpr requires the value to be known at compile time.

#include <iostream>
#include <string>

int main() {
    int a = 10;            // copy initialization
    int b(20);             // direct initialization
    int c{30};             // brace (uniform) initialization – rejects narrowing
    int d{};               // value initialization: 0
    auto e = 2.5;          // type deduced: double
    auto name = std::string{"Asha"};
    const int max_users = 100;            // read-only after initialization
    constexpr int seconds_per_day = 24 * 60 * 60;   // computed at compile time

    std::cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << ' ' << name << '\n';
    std::cout << max_users << ' ' << seconds_per_day << '\n';
    return 0;
}

Output

10 20 30 0 2.5 Asha
100 86400

Operators and precedence

C++ evaluates *, / and % before + and -, relational operators before && and ||, and assignment last. Operators of the same level group left to right – except assignment and the conditional operator, which group right to left. When in doubt, add parentheses: they cost nothing and make intent clear.

Level (high → low)Operators
1::
2a++ a-- f() a[i] . ->
3++a --a ! ~ unary - * & sizeof new delete (casts)
4* / %
5+ -
6<< >>
7<=> (C++20 three-way comparison)
8< <= > >=
9== !=
10–12& then ^ then |
13–14&& then ||
15?: = += -= *= /= … (right to left)
16,
#include <iostream>

int main() {
    int a = 2 + 3 * 4;              // * before +            → 14
    int b = (2 + 3) * 4;            // parentheses first     → 20
    int c = 20 - 6 - 4;             // left to right         → 10
    int d, e;
    d = e = 7;                      // assignment: right to left
    bool in_range = a > 10 && a < 20;            // relational before &&
    int f = 17 % 5 * 2;             // % and * same level, left to right → 4
    std::cout << a << ' ' << b << ' ' << c << ' ' << d << e << ' ' << in_range << ' ' << f << '\n';
    int x = 5;
    x += 3;                         // compound assignment: x = x + 3
    x *= 2;
    std::cout << x << ' ' << (x > 15 ? "big" : "small") << '\n';
    return 0;
}

Output

14 20 10 77 1 4
16 big

Because << binds tighter than comparison and the conditional operator, write std::cout << (a > b) and std::cout << (x ? "yes" : "no") with parentheses.

Type aliases and integer promotion

using Name = type; (or the older typedef) gives a type a second, more meaningful name. Fixed-width types such as std::int32_t and std::uint8_t come from <cstdint>. In arithmetic, types smaller than int (char, short, bool) are first promoted to int – which is also why 'A' + 1 prints 66.

#include <cstdint>
#include <iostream>

using Marks = int;                   // modern type alias
typedef double Rupees;               // the older way, same effect
using u8 = std::uint8_t;             // fixed-width type from <cstdint>

int main() {
    Marks m = 92;
    Rupees fee = 1499.50;
    u8 level = 250;
    level += 10;                     // unsigned 8-bit wraps: 260 - 256 = 4
    short s1 = 30000, s2 = 30000;
    auto sum = s1 + s2;              // shorts are promoted to int before adding
    std::cout << m << ' ' << fee << ' ' << +level << ' ' << sum << ' ' << sizeof(sum) << '\n';
    return 0;
}

Output

92 1499.5 4 60000 4

Type conversions

Mixed arithmetic converts to the "wider" type (int + double → double). Integer division discards the fraction. Use static_cast<T>(x) for an explicit, searchable conversion instead of a C-style cast.

#include <iostream>

int main() {
    int total = 7, count = 2;
    std::cout << total / count << '\n';                          // integer division: 3
    std::cout << static_cast<double>(total) / count << '\n';     // 3.5
    std::cout << static_cast<int>(3.99) << ' ' << static_cast<int>(-3.99) << '\n';   // truncates toward zero
    char grade = 'A';
    std::cout << grade + 1 << ' ' << static_cast<char>(grade + 1) << '\n';          // int 66, char B
    unsigned int u = -1;                                         // wraps around (well defined)
    std::cout << u << '\n';
    std::cout << std::boolalpha << (5 > 3) << ' ' << std::noboolalpha << (5 > 3) << '\n';
    return 0;
}

Output

3
3.5
3 -3
66 B
4294967295
true 1

Reading input with std::cin

std::cin >> x reads a value of x's type, skipping leading whitespace. Several values can be chained. (Input is covered fully in Input/Output with cin and cout.)

#include <iostream>
#include <string>

int main() {
    std::string name;
    int age = 0;
    double height = 0;
    std::cout << "Name, age and height: ";
    std::cin >> name >> age >> height;         // >> skips whitespace between values
    std::cout << '\n' << name << " is " << age << " and " << height << " m tall\n";
    return 0;
}

Input

Ravi 21 1.75

Output

Name, age and height:
Ravi is 21 and 1.75 m tall

Namespaces and the scope resolution operator

Namespaces group names to avoid clashes – the whole standard library lives in std. ::name refers to the global name, ns::name to a namespace member. using namespace std; saves typing in small programs but is avoided in headers and large projects because it pulls hundreds of names into scope.

#include <iostream>

int value = 1;                 // global

namespace billing {
    int value = 2;             // billing::value
    double tax(double amount) { return amount * 0.18; }
}

int main() {
    int value = 3;             // local hides the global
    std::cout << value << ' ' << ::value << ' ' << billing::value << '\n';
    std::cout << billing::tax(500) << '\n';
    {
        using namespace billing;   // only inside this block
        std::cout << tax(100) << '\n';
    }
    return 0;
}

Output

3 1 2
90
18

Modern formatted output: std::format and std::print

C++20 std::format builds strings with Python-style placeholders, and C++23 std::print/std::println print them directly – type-safe and usually faster than iostreams.

#include <format>
#include <print>
#include <string>

int main() {
    std::string item = "Notebook";
    int qty = 3;
    double price = 45.5;
    std::string line = std::format("{:<10}|{:>4}|{:>8.2f}", item, qty, qty * price);
    std::println("{}", line);                       // C++23: print with a newline
    std::println("{0} x {1} = {2}, again {0}", qty, price, qty * price);
    std::println("hex {:x}, binary {:b}, padded {:05}", 255, 5, 42);
    return 0;
}

Output

Notebook  |   3|  136.50
3 x 45.5 = 136.5, again 3
hex ff, binary 101, padded 00042

Common beginner mistakes

  • Integer division: double avg = total / count; divides as int first – cast one side.
  • Uninitialized variables: a local int sum; holds garbage – write int sum = 0;.
  • = instead of ==: if (x = 5) assigns and is always true.
  • Signed overflow: int past 2,147,483,647 is undefined behaviour – use long long.
  • Mixing signed and unsigned: -1 < 1u is false because −1 converts to a huge unsigned value.
  • Floating-point equality: 0.1 + 0.2 == 0.3 is false – compare with a tolerance.

Key points to remember

  • Execution starts in main(); the standard library is in namespace std.
  • sizeof(char) is 1; int is typically 4 bytes and long long 8.
  • Prefer brace initialization – it catches narrowing conversions.
  • constexpr = compile-time constant; const = read-only after initialization.
  • 7 / 2 is 3; cast one operand to double for 3.5.

Frequently asked questions

Is "using namespace std" bad practice?

In small programs and exercises it is harmless. In header files and larger code bases it can cause name clashes, so professionals write std:: explicitly.

What is the difference between C and C++ syntax?

C++ is almost a superset of C, adding classes, references, namespaces, templates, overloading, bool as a built-in type, iostreams and much more. Most C code compiles as C++ with small changes.

Which C++ version should I learn?

Learn modern C++ (C++17 and C++20); the features of C++23 such as std::print are already available in current compilers.

Where can I learn more?

Read C++ Hello World and C++ Variables and Data Types, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links