Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 1 – Start here: toolchains, compiling and first programs

C++ program structure, naming and formatting

Lay out a small C++ program in functions and blocks, pick one naming style, format code with clang-format, and see why using namespace std; causes clashes.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Organise a small program into functions and blocks
  • Apply consistent formatting with clang-format
  • Explain why 'using namespace std;' must never appear in a header
  • Choose names in one style, and comments that say why rather than what

Before you start

clang-format --dry-run --Werror found 39 places to change in a C++ file of seven lines, and a 13-line program stopped compiling on both compilers because of one line, using namespace std;. A C++ program that others can read follows a few conventions: a file runs from its #include lines to main, the work is split into small functions with names that say what they do, every block is indented the same way, and names from std are written as std:: names. None of this changes what the compiler produces, but it decides how quickly you, a teammate or an examiner can find a mistake.

The sections below show the usual layout of a small program, how braces limit where a name exists, how to choose names, how clang-format formats a whole file in one command, and why using namespace std; breaks a program that has a variable called count.

A small program reads top to bottom in six parts

This program counts the fours and sixes in an innings, read ball by ball from standard input:

A small program in six parts C++ · boundaries.cpp
// Counts the fours and sixes in an innings, read ball by ball from standard input.
#include <iostream>
#include <print>
#include <vector>

constexpr int four_runs = 4;
constexpr int six_runs = 6;

std::vector<int> read_runs();
int count_boundaries(const std::vector<int>& runs);

int main() {
    const std::vector<int> runs = read_runs();
    std::println("{} balls, {} boundaries", runs.size(), count_boundaries(runs));
}

// Reads whole numbers until the input ends or holds something that is not a number.
std::vector<int> read_runs() {
    std::vector<int> runs;
    int run = 0;
    while (std::cin >> run) {
        runs.push_back(run);
    }
    return runs;
}

int count_boundaries(const std::vector<int>& runs) {
    int boundaries = 0;
    for (int run : runs) {
        if (run == four_runs || run == six_runs) {
            ++boundaries;
        }
    }
    return boundaries;
}
Built with both compilers, given seven balls Python · boundaries_session.py
from session import run

run("""
cat innings.txt
clang++ -std=c++23 -Wall -Wextra -Wpedantic boundaries.cpp -o boundaries && ./boundaries < innings.txt
g++-16 -std=c++23 -Wall -Wextra -Wpedantic boundaries.cpp -o boundaries && ./boundaries < innings.txt
""")

Output

$ cat innings.txt
1 4 0 6
2 4 1
$ clang++ -std=c++23 -Wall -Wextra -Wpedantic boundaries.cpp -o boundaries && ./boundaries < innings.txt
7 balls, 3 boundaries
$ g++-16 -std=c++23 -Wall -Wextra -Wpedantic boundaries.cpp -o boundaries && ./boundaries < innings.txt
7 balls, 3 boundaries

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 boundaries_session.py

With 1 4 0 6 and 2 4 1 as input it printed 7 balls, 3 boundaries. Read from the top, the file has six parts:

The order of a one-file program: a comment, the includes, named constants, declarations, main, then the helper definitions.1. A commentwhat the program does2. #include linesone per header used3. Named constantsconstexpr int four_runs = 4;4. Declarationsof the helper functions5. int main()the outline of the program6. Definitionsof the helper functions

One file, top to bottom

Text description of the diagram

The diagram shows six numbered boxes, in two columns, in the order they appear in the file boundaries.cpp.

  1. A comment that says what the program does.
  2. The #include lines, one for each header the file uses.
  3. Named constants, such as constexpr int four_runs = 4;.
  4. Declarations of the helper functions, so that main can call them before their definitions.
  5. int main(), which reads as an outline of the whole program.
  6. The definitions of the helper functions.
  • A comment on the first line says what the program is for.
  • The #include lines, one per header that the file uses, here sorted alphabetically.
  • Named constants replace bare numbers: four_runs says what 4 means, and constexpr makes it a constant the compiler knows at compile time.
  • Declarations such as int count_boundaries(const std::vector<int>& runs); tell the compiler that a function exists, so main can call it before its definition.
  • main stays short and reads like an outline: read the runs, count the boundaries, print the result.
  • The definitions of the helper functions follow, each doing one job.

Putting the helpers first and main last also works, and then the declarations are not needed. Pick one order for a project and keep it. When a program grows past a few hundred lines, the declarations move into a header file, which the lesson on headers covers.

That order is for the reader. When the program runs, it starts in main, which hands each job to a helper. Step through one run with innings.txt as the input, call by call:

Interactive · message by message One run of boundaries.cpp, call by call Step through main and its two helper functions with innings.txt as the input. Each arrow is a call or a result.
One run of boundaries.cpp, call by call, step 6 of 6. Messages so far: main to read_runs: read_runs(); read_runs to main: 7 runs; main to count_boundaries: runs, by const reference; count_boundaries to main: 3.main7 balls, 3 boundariesread_runsreads 1 4 0 6 2 4 1count_boundaries4, 6 and 4: 3read_runs()7 runsruns, by const reference3

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. main calls read_runs. Line 13 calls read_runs(). The declaration on line 9 told the compiler that the function exists, so main can call it before its definition on line 18.
  2. Reading the innings. read_runs reads whole numbers until the input ends: 1, 4, 0 and 6 from the first line of innings.txt, then 2, 4 and 1 from the second.
  3. Seven runs back. It returns the seven numbers in a vector, which main keeps as runs.
  4. main calls count_boundaries. Line 14 passes runs to count_boundaries, whose parameter is a const std::vector<int>&: the function reads the vector of main without copying it.
  5. Counting the boundaries. It compares each run with four_runs and six_runs. The 4, the 6 and the second 4 match, so boundaries reaches 3.
  6. The answer. It returns 3, and main prints 7 balls, 3 boundaries, with both compilers. The body of main stayed two lines long: one reads the runs, the other counts and prints.

Checkpoint

Check: The parts of a small program

  1. Question 1 of 2 Why does boundaries.cpp have the lines std::vector<int> read_runs(); and int count_boundaries(const std::vector<int>& runs); above main?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: They tell the compiler that the two functions exist, so main can call them before their definitions further down

    Declarations such as int count_boundaries(const std::vector<int>& runs); tell the compiler that a function exists, so main can call it before its definition. Putting the helpers first and main last works too; pick one order for a project and keep it.

  2. Question 2 of 2 What should main look like in the layout of this lesson?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Short, and reading like an outline: read the runs, count the boundaries, print the result

    The file runs from a purpose comment and the #include lines, through named constants and declarations, to a short main and then the definitions of the helper functions, each doing one job.

A name declared in a block ends at its closing brace

A pair of braces makes a block, and a name declared inside a block exists only until its closing brace. The part of the program where a name can be used is its scope: The part of a program in which a name can be used. A name declared inside a block, the code between a pair of braces, can be used from its declaration up to the block's closing brace.:

A name used after its block has ended C++ · scope.cpp
#include <iostream>

int main() {
    int runs = 7;
    if (runs > 6) {
        int bonus = runs - 6;
        std::cout << "Bonus: " << bonus << '\n';
    }
    std::cout << "Bonus again: " << bonus << '\n';
}
Both compilers stop at line 9 Python · scope_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -c scope.cpp -o scope.o
g++-16 -std=c++23 -Wall -Wextra -c scope.cpp -o scope.o
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -c scope.cpp -o scope.o
scope.cpp:9:37: error: use of undeclared identifier 'bonus'
    9 |     std::cout << "Bonus again: " << bonus << '\n';
      |                                     ^~~~~
1 error generated.
[exit status 1]
$ g++-16 -std=c++23 -Wall -Wextra -c scope.cpp -o scope.o
scope.cpp: In function 'int main()':
scope.cpp:9:37: error: 'bonus' was not declared in this scope
    9 |     std::cout << "Bonus again: " << bonus << '\n';
      |                                     ^~~~~
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 scope_session.py

bonus is declared inside the if block, so on line 9, after the closing brace, it no longer exists. Clang said use of undeclared identifier 'bonus' and GCC said 'bonus' was not declared in this scope. Declare a name in the smallest block that needs it, and declare it outside the block when code after the block needs it too. Small scopes keep names from being changed by code that has no business with them, and every function body is a block of its own.

Step through the file as the compiler reads it, and watch where each of its two names can be used:

Interactive · step by step Where runs and bonus can be used in scope.cpp Step through the file as the compiler reads it. Each name can be used only inside the block that declares it.
Where runs and bonus can be used in scope.cpp, step 6 of 6. Showing the block of main, runs, the if block (closed on line 8), bonus (ends on line 8), line 7 uses bonus, line 9 uses bonus, 9:37 undeclared 'bonus'. In focus: the block of main.the block of mainlines 3 to 10runsdeclared on line 4the if blockclosed on line 8bonusends on line 8line 7 uses bonusline 9 uses bonus9:37 undeclared 'bonus'both compilers stop

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. runs. Line 4 declares runs in the block of main, so it can be used from there to the closing brace of main on line 10.
  2. A block inside main. Line 5 opens the if block, and line 6 declares bonus inside it. Its scope runs from line 6 to the brace on line 8.
  3. Used inside the block. Line 7 uses bonus inside the block, which is fine.
  4. The block ends. The closing brace on line 8 ends the if block, and the name bonus ends with it.
  5. Used after the block. Line 9 uses bonus after the block. Both compilers stop there, at column 37: Clang with use of undeclared identifier 'bonus', GCC with 'bonus' was not declared in this scope.
  6. Where to declare it. If code after the block needs the value, declare bonus before the if, in the block of main. If not, keep it where it is: in the smallest block that needs it.

Key idea

A name can be used from its declaration to the closing brace of its block, and nowhere else: declare it in the smallest block that needs it.

Checkpoint

Check: Blocks and scope

  1. Question 1 of 2 The last line must print the bonus too. Which change makes this compile?

    Read the code, then choose one answer.

    int runs = 7;
    if (runs > 6) {
        int bonus = runs - 6;
        std::cout << "Bonus: " << bonus << '\n';
    }
    std::cout << "Bonus again: " << bonus << '\n';
    Show the answer: Question 1 of 2

    Answer: Declare int bonus = 0; before the if, and assign bonus = runs - 6; inside it

    A name declared inside a block exists only until its closing brace. Declare a name in the smallest block that needs it, and outside the block when code after the block needs it too.

  2. Question 2 of 2 A counter is needed only inside one for loop. Where should it be declared?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: In the loop itself, as in for (int i = 0; …), so that it ends with the loop

    Small scopes keep names from being changed by code that has no business with them. A name declared in a loop's header exists only inside that loop.

Pick one naming style and use it everywhere

C++ itself does not prescribe a naming style, and well-known style guides disagree:

Style Types Functions Variables Constants
The standard library snake_case (std::string, std::vector) snake_case (push_back) snake_case snake_case
C++ Core Guidelines Prefer underscore_style names (rule NL.10)
Google C++ Style Guide PascalCase PascalCase snake_case kPascalCase
LLVM Coding Standards PascalCase camelCase PascalCase

The Core Guidelines’ rule NL.8, “Use a consistent naming style”, matters more than which style you choose. This track uses the standard library’s style, snake_case for everything, so its own names look like the library names around them. Whatever the style:

  • Name things for what they are: boundaries, not b; read_runs, not func2. Short names such as i are fine for a loop counter that lives for three lines.
  • Name functions for what they do: a verb, such as count_boundaries.
  • Never start a name with an underscore and a capital letter, and never use two underscores in a row. The standard reserves such names for the compiler and the library, and names that start with an underscore are reserved at global scope too.

Which style to choose

In code that already has a style, follow it. In a project of your own, the standard library’s snake_case is an easy choice to keep, because your names then look like the library names they sit beside.

Case Converter Turn a phrase or an old name into snake_case, camelCase or PascalCase while you rename.

Checkpoint

Check: One naming style

  1. Question 1 of 2 In this track's style, which is the best name for a function that counts the wickets in an innings?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: count_wickets

    Name functions for what they do, with a verb, in the project's one style. This track uses the standard library's snake_case for everything.

  2. Question 2 of 2 What does rule NL.8 of the C++ Core Guidelines ask for?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A consistent naming style

    The style guides disagree: the standard library uses snake_case, Google's guide PascalCase for types and functions, LLVM's camelCase for functions. NL.8, "Use a consistent naming style", is the rule they share.

clang-format sets the layout of a whole file in one command

Formatting by hand is slow and never quite consistent. clang-format rewrites the layout of a file to a chosen style, without touching what the code does. This file was typed with no care at all:

Before: messy.cpp C++ · style/messy.cpp
#include <vector>
#include <iostream>
int Total(const std::vector<int>&v){int t=0;
for(int x:v){ if(x>0)
t+=x;}
  return t;}
int main( ) {
std::vector<int> runs {4,0,6,1,   2};
    std::cout<<"Total: "<<Total(runs)<<'\n';
      return 0;
}
Two preset styles Python · presets_session.py
from session import run

# On macOS, xcrun runs the clang-format of the Xcode Command Line Tools.
run("""
xcrun clang-format --version
xcrun clang-format --style=llvm style/messy.cpp
xcrun clang-format --style=google style/messy.cpp
""")

Output

$ xcrun clang-format --version
Apple clang-format version 21.0.0 (clang-2100.3.34.2)
$ xcrun clang-format --style=llvm style/messy.cpp
#include <iostream>
#include <vector>
int Total(const std::vector<int> &v) {
  int t = 0;
  for (int x : v) {
    if (x > 0)
      t += x;
  }
  return t;
}
int main() {
  std::vector<int> runs{4, 0, 6, 1, 2};
  std::cout << "Total: " << Total(runs) << '\n';
  return 0;
}
$ xcrun clang-format --style=google style/messy.cpp
#include <iostream>
#include <vector>
int Total(const std::vector<int>& v) {
  int t = 0;
  for (int x : v) {
    if (x > 0) t += x;
  }
  return t;
}
int main() {
  std::vector<int> runs{4, 0, 6, 1, 2};
  std::cout << "Total: " << Total(runs) << '\n';
  return 0;
}

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 presets_session.py

clang-format --style=llvm messy.cpp printed the file in LLVM’s style, two-space indentation and 80 columns, with const std::vector<int> &v and the body of the if on its own line. --style=google printed const std::vector<int>& v and kept if (x > 0) t += x; on one line. Both sorted the two #include lines. clang-format is part of the LLVM tools: install it with your compiler’s LLVM package or a package manager. On this track’s Mac it came with the Xcode Command Line Tools, and xcrun clang-format runs it.

A project writes its choice down in a file named .clang-format (or _clang-format) in its top folder. clang-format looks for that file in the folder of each source file and the folders above it, and editors that run clang-format use it too. This is the style of this track’s examples:

The track's formatting rules Code · style/_clang-format
# This track's formatting: LLVM's style with 4-space indentation, 100 columns, & next to the type,
# and a short if on one line when it has no else.
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 100
PointerAlignment: Left
AllowShortIfStatementsOnASingleLine: WithoutElse

BasedOnStyle: LLVM starts from LLVM’s rules and the other lines change four of them. With that file next to messy.cpp, plain clang-format messy.cpp uses it:

After: the track's rules, and two checks Python · track_style_session.py
from session import run

# With no --style, clang-format reads style/_clang-format, next to the file.
run("""
xcrun clang-format style/messy.cpp
xcrun clang-format --dry-run --Werror style/scores.cpp 2>&1 | grep -c "error:"
xcrun clang-format --dry-run --Werror style/scores_solution.cpp && echo "nothing to change"
""")

Output

$ xcrun clang-format style/messy.cpp
#include <iostream>
#include <vector>
int Total(const std::vector<int>& v) {
    int t = 0;
    for (int x : v) {
        if (x > 0) t += x;
    }
    return t;
}
int main() {
    std::vector<int> runs{4, 0, 6, 1, 2};
    std::cout << "Total: " << Total(runs) << '\n';
    return 0;
}
$ xcrun clang-format --dry-run --Werror style/scores.cpp 2>&1 | grep -c "error:"
39
$ xcrun clang-format --dry-run --Werror style/scores_solution.cpp && echo "nothing to change"
nothing to change

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 track_style_session.py

Step through how clang-format chose those rules for messy.cpp, and what it changed with them:

Interactive · stage by stage How clang-format found the track's rules Step through the run of clang-format on messy.cpp with no --style option, from the search to the output.
How clang-format found the track's rules, step 6 of 6. Showing clang-format messy.cpp, Look beside the file, Found _clang-format, BasedOnStyle: LLVM, Four lines change them, The file. In focus: The file.clang-format messy.cppno --style optionLook beside the filestyle/, then the folders aboveFound _clang-formatin style/BasedOnStyle: LLVMLLVM's rules to start withFour lines change them4 spaces, 100 columns, & …The filenames left as they were

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. No style given. clang-format messy.cpp is given no --style option, so it looks for a style file instead.
  2. The search. It looks in the folder of the source file, style/, and then in the folders above it, for a file named .clang-format or _clang-format.
  3. The track's file. It finds style/_clang-format, the track's file, right beside messy.cpp.
  4. LLVM's rules first. BasedOnStyle: LLVM starts from LLVM's own rules, the ones --style=llvm used: two-space indentation and a limit of 80 columns.
  5. Four changes. The other four lines change four of those rules: 4-space indentation, 100 columns, & next to the type, and a short if without else kept on one line.
  6. The result. The output has 4-space indentation, const std::vector<int>& v and if (x > 0) t += x; on one line. The names Total, t, v and x are unchanged: no formatter renames anything.

clang-format fixed the layout but not the names: Total, t, v and x say nothing about the data, and no formatter renames them for you. The session’s last two commands are checks: --dry-run --Werror found 39 places to change in the exercise file scores.cpp further down, and nothing in its solution. Three commands cover daily use:

Command What it does
clang-format -i main.cpp Rewrites the file in place
clang-format --dry-run --Werror main.cpp Changes nothing, and fails with one error for each place that is not formatted; useful in CI
clang-format --style=llvm --dump-config > .clang-format Writes a complete style file to start from

Run the formatter before every commit, or let the editor run it on save, so that changes to a file show only real edits, never reformatted lines.

Text Diff Paste a file before and after clang-format to see every line it changed.

Checkpoint

Check: Formatting with clang-format

  1. Question 1 of 3 Which command checks, without changing anything, that a file already follows the project's .clang-format, and fails if it does not?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: clang-format --dry-run --Werror main.cpp

    --dry-run makes no changes and reports each place that is not formatted, and --Werror turns those reports into errors, so the command fails. -i rewrites the file, and --dump-config prints the style settings.

  2. Question 2 of 3 After clang-format -i messy.cpp with the track's style file, what is still wrong with the file?

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: The names: Total, t, v and x still say nothing about the data

    clang-format rewrites the layout of a file to a chosen style without touching what the code does. It fixed the layout of messy.cpp but not the names, which is why the exercise asks you to rename too.

  3. Question 3 of 3 messy.cpp sits in the folder style/, next to _clang-format. With no --style option, which rules does clang-format messy.cpp use?

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: The file style/_clang-format: LLVM's rules with 4-space indentation and three other changes

    A project writes its choice down in .clang-format or _clang-format in its top folder. clang-format looks for that file in the folder of each source file and the folders above it, and editors that run clang-format use it too.

using namespace std; can make your own names ambiguous

using namespace std; makes every name of namespace: A named scope that groups names so that they cannot collide: the standard library's names are in namespace std, so std::count and a program's own count are two different names. std usable without std::. Such a line is called a using-directive: A line such as using namespace std; that makes every name of a namespace usable without its prefix, from that line to the end of the scope it is written in. In a header, it reaches every file that includes the header.. Short programs often start with it, and it fails in a way that is hard to predict:

A global named count C++ · count_clash.cpp
#include <iostream>
using namespace std;

int count = 0;

int main() {
    for (int run : {4, 0, 6, 1}) {
        if (run == 4 || run == 6) {
            ++count;
        }
    }
    cout << "Boundaries: " << count << '\n';
}
Ambiguous on both compilers Python · count_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -c count_clash.cpp -o count_clash.o
g++-16 -std=c++23 -Wall -Wextra -c count_clash.cpp -o count_clash.o
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -c count_clash.cpp -o count_clash.o
count_clash.cpp:9:15: error: reference to 'count' is ambiguous
    9 |             ++count;
      |               ^
count_clash.cpp:4:5: note: candidate found by name lookup is 'count'
    4 | int count = 0;
      |     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__algorithm/count.h:86:1: note: candidate found by name lookup is 'std::count'
   86 | count(_InputIterator __first, _InputIterator __last, const _Tp& __value) {
      | ^
count_clash.cpp:12:31: error: reference to 'count' is ambiguous
   12 |     cout << "Boundaries: " << count << '\n';
      |                               ^
count_clash.cpp:4:5: note: candidate found by name lookup is 'count'
    4 | int count = 0;
      |     ^
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__algorithm/count.h:86:1: note: candidate found by name lookup is 'std::count'
   86 | count(_InputIterator __first, _InputIterator __last, const _Tp& __value) {
      | ^
2 errors generated.
[exit status 1]
$ g++-16 -std=c++23 -Wall -Wextra -c count_clash.cpp -o count_clash.o
count_clash.cpp: In function 'int main()':
count_clash.cpp:9:15: error: reference to 'count' is ambiguous
    9 |             ++count;
      |               ^~~~~
  • there are 2 candidates
In file included from /opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/bits/unicode.h:39,
                 from /opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/format:62,
                 from /opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/ostream:45,
                 from /opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/iostream:43,
                 from count_clash.cpp:1:
    • candidate 1: 'template<class _IIter, class _Tp> constexpr typename std::iterator_traits<_Iterator>::difference_type std::count(_IIter, _IIter, const _Tp&)'
      /opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/bits/stl_algo.h:4046:5:
       4046 |     count(_InputIterator __first, _InputIterator __last, const _Tp& __value)
            |     ^~~~~
    • candidate 2: 'int count'
      count_clash.cpp:4:5:
          4 | int count = 0;
            |     ^~~~~
count_clash.cpp:12:31: error: reference to 'count' is ambiguous
   12 |     cout << "Boundaries: " << count << '\n';
      |                               ^~~~~
  • there are 2 candidates
    • candidate 1: 'template<class _IIter, class _Tp> constexpr typename std::iterator_traits<_Iterator>::difference_type std::count(_IIter, _IIter, const _Tp&)'
      /opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/bits/stl_algo.h:4046:5:
       4046 |     count(_InputIterator __first, _InputIterator __last, const _Tp& __value)
            |     ^~~~~
    • candidate 2: 'int count'
      count_clash.cpp:4:5:
          4 | int count = 0;
            |     ^~~~~
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 count_session.py

Both compilers rejected line 9 with reference to 'count' is ambiguous: the program’s global count and the standard library’s algorithm std::count are both visible, and the compiler cannot choose. This file includes only <iostream>, yet std::count was there anyway, because both libraries’ <iostream> include parts of the algorithms library: Clang’s note pointed into libc++’s __algorithm/count.h, and GCC’s into libstdc++’s stl_algo.h. A program can compile today and break when the next version of a library includes one header more.

Step through what the compiler can see when it reaches ++count on line 9, and then the fix:

Interactive · step by step Two names called count on line 9 Step through what the compiler can see when it reaches ++count on line 9 of count_clash.cpp, then the fix.
Two names called count on line 9, step 5 of 5. Showing #include <iostream>, std::count, using namespace std;, ++count; on line 9, int count = 0;, reference to 'count', boundary_count, Boundaries: 2. In focus: boundary_count, Boundaries: 2.declaresno std:: needed#include <iostream>the only includestd::countan algorithm of stdusing namespace std;line 2++count; on line 9int count = 0;line 4: the program's ownreference to 'count'is ambiguousboundary_countand std:: namesBoundaries: 2both compilers

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. One include. The file includes only <iostream>, yet std::count is declared: Clang's note points into libc++'s __algorithm/count.h, and GCC's into libstdc++'s stl_algo.h.
  2. The directive. using namespace std; on line 2 makes every name of std usable without std::, std::count among them.
  3. The program's own count. Line 4 declares a global variable that is also called count.
  4. Two candidates. On line 9, ++count finds both names, and the compiler cannot choose between them. Both compilers stop with reference to 'count' is ambiguous, and do so again on line 12.
  5. The fix. Without the directive and with a specific name, boundary_count, nothing can collide: the fixed file prints Boundaries: 2 with both compilers.

There are three fixes, and the first is the rule this track follows:

  • Write std:: names: std::cout, std::vector. It costs five characters and never clashes.
  • Name the few things you use: using std::cout; brings in only that one name.
  • Keep your own names specific: boundary_count would not have clashed even with using namespace std;.
The fix: std:: names and a specific name C++ · count_fixed.cpp
#include <iostream>

int boundary_count = 0;

int main() {
    for (int run : {4, 0, 6, 1}) {
        if (run == 4 || run == 6) {
            ++boundary_count;
        }
    }
    std::cout << "Boundaries: " << boundary_count << '\n';
}
Built and run Python · count_fixed_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -Wpedantic count_fixed.cpp -o count_fixed && ./count_fixed
g++-16 -std=c++23 -Wall -Wextra -Wpedantic count_fixed.cpp -o count_fixed && ./count_fixed
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -Wpedantic count_fixed.cpp -o count_fixed && ./count_fixed
Boundaries: 2
$ g++-16 -std=c++23 -Wall -Wextra -Wpedantic count_fixed.cpp -o count_fixed && ./count_fixed
Boundaries: 2

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 count_fixed_session.py

It printed Boundaries: 2. In a header file, using namespace std; is never acceptable, because a header is pasted into every file that includes it: the directive then applies to code whose authors never wrote it and cannot undo it. The C++ Core Guidelines make this their rule SF.7, which rules out a global using namespace in any header, and their rule SF.6 keeps it elsewhere for transition, for foundation libraries such as std, or for a local scope. Google’s style guide forbids using-directives altogether, and LLVM’s rule is not to use using namespace std;, in headers above all.

Key idea

Write std:: names. Your own names then never compete with the names of std, whatever the library’s headers bring in, and a header passes nothing on to the files that include it.

Checkpoint

Check: using namespace std; and name clashes

  1. Question 1 of 2 Why is using namespace std; never acceptable in a header file?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A header is pasted into every file that includes it, so the directive applies to code whose authors never wrote it and cannot undo it

    A header is pasted into every file that includes it, so a using-directive there spreads to code whose authors never asked for it. Write std:: names in headers.

  2. Question 2 of 2 With using namespace std; still in the file, which change alone stops the global count from clashing with std::count?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Rename the global to boundary_count

    Three fixes work: write std:: names, name only the few things you use (using std::cout;), or keep your own names specific. This track writes std:: names.

A comment should say why, not repeat what the code says

A comment that repeats the code goes stale and helps nobody: ++boundaries; // add one to boundaries. A useful comment says what the code cannot: why it does something, what it assumes, or what the reader would otherwise get wrong. The Core Guidelines make this two rules: NL.1 keeps out of comments what the code already says clearly, and NL.2 asks comments to state the intent. boundaries.cpp has two comments of that kind, on its purpose and on when read_runs stops reading. Good names make most other comments unnecessary.

Here are the three comments side by side, the first one made up and the other two from boundaries.cpp:

Comment Worth keeping?
// add one to boundaries, after ++boundaries; No: it repeats the code and goes stale
// Counts the fours and sixes …, on line 1 Yes: it says what the program is for
// Reads whole numbers until …, on line 17 Yes: it says when read_runs stops

The first row is what rule NL.1 keeps out of comments; the other two state the intent, as rule NL.2 asks.

Checkpoint

Check: Comments that say why

  1. One question Which of these comments is worth keeping?

    Choose one answer.

    Show the answer: One question

    Answer: // Reads whole numbers until the input ends or holds something that is not a number.

    A useful comment says what the code cannot: why it does something, what it assumes, or what the reader would otherwise get wrong. boundaries.cpp has two such comments, on its purpose and on when read_runs stops reading.

Exercise: format and rename a program

This program works and prints 73.6667, but it breaks almost every rule of this lesson:

scores.cpp C++ · style/scores.cpp
#include<iostream>
#include<vector>
using namespace std;
int CNT=0;
double AVG(vector<int> V){double S=0;for(int i=0;i<V.size();i++){S=S+V[i];}return S/V.size();}
int main(){vector<int> MarksList={72,85,64};
cout<<AVG(MarksList)<<endl;}

Copy it, together with _clang-format, into a folder of your own. Then:

  1. Remove using namespace std; and write std:: names.
  2. Rename everything in the track’s style, remove the unused global, and take the vector as const std::vector<int>& instead of copying it.
  3. Run clang-format -i scores.cpp, then check with clang-format --dry-run --Werror scores.cpp, which must print nothing.

The program must still print 73.6667, and it must build without warnings with -std=c++23 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror.

One solution

scores.cpp in the track's style C++ · style/scores_solution.cpp
#include <iostream>
#include <vector>

double average(const std::vector<int>& marks) {
    double sum = 0;
    for (int mark : marks) {
        sum += mark;
    }
    return sum / static_cast<double>(marks.size());
}

int main() {
    const std::vector<int> marks{72, 85, 64};
    std::cout << average(marks) << '\n';
}
The original, then the solution with every flag Python · scores_session.py
from session import run

run("""
clang++ -std=c++23 style/scores.cpp -o scores && ./scores
clang++ -std=c++23 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror style/scores_solution.cpp -o scores_solution && ./scores_solution
g++-16 -std=c++23 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror style/scores_solution.cpp -o scores_solution && ./scores_solution
""")

Output

$ clang++ -std=c++23 style/scores.cpp -o scores && ./scores
73.6667
$ clang++ -std=c++23 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror style/scores_solution.cpp -o scores_solution && ./scores_solution
73.6667
$ g++-16 -std=c++23 -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Werror style/scores_solution.cpp -o scores_solution && ./scores_solution
73.6667

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 scores_session.py

It printed 73.6667, built without a warning under those flags with both compilers, and clang-format --dry-run --Werror printed nothing for it. The range-based for also removed the comparison of an int with size().

Check yourself

With your version of scores.cpp done, answer the questions below. Each one targets the idea you have shown least so far, steps up when you answer well, and says why every choice is right or wrong:

Practice that adapts to you

Practise this lesson

13 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 13 In the lesson's layout of a one-file program, what comes right after the #include lines?

    Choose one answer.

    Show the answer: Question 1 of 13

    Answer: Named constants, such as constexpr int four_runs = 4;

    Read from the top, the file has six parts: a purpose comment, the #include lines, named constants, declarations, main, and the definitions of the helper functions.

  2. Question 2 of 13 Why does boundaries.cpp compare with four_runs instead of writing 4 in the test?

    Choose one answer.

    Show the answer: Question 2 of 13

    Answer: The name says what the 4 means, and constexpr makes it a constant the compiler knows

    constexpr int four_runs = 4; says what 4 means, and constexpr makes it a constant the compiler knows at compile time. The test then reads run == four_runs || run == six_runs.

  3. Question 3 of 13 A one-file program has grown to 600 lines and forty helper functions, and a second program needs ten of the same helpers. Where do the declarations of those helpers go?

    Choose one answer.

    Show the answer: Question 3 of 13

    Answer: Into a header file that both programs include

    The layout of this lesson is for small programs. When a program grows past a few hundred lines, the declarations move into a header file, which the lesson on headers covers, and every file that includes the header sees the same declarations.

  4. Question 4 of 13 A variable is declared inside the braces of an if statement. Where can it be used?

    Choose one answer.

    Show the answer: Question 4 of 13

    Answer: Only inside that block, up to its closing brace

    A name's scope ends at the closing brace of the block that declares it. The lesson's bonus, declared inside the if block, was unknown on the line after the block: "use of undeclared identifier 'bonus'".

  5. Question 5 of 13 scope.cpp declares bonus inside the if block and prints it again on line 9, after the block. What happens?

    Choose one answer.

    Show the answer: Question 5 of 13

    Answer: It does not compile; both compilers report bonus as undeclared at line 9

    bonus is declared inside the if block, so on line 9, after the closing brace, it no longer exists. Both compilers stopped there.

  6. Question 6 of 13 Which of these names should a program never declare? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 6 of 13

    Answer:

    • _Total
    • run__count

    The standard reserves every name that begins with an underscore followed by a capital letter, and every name that contains a double underscore, for the compiler and its library. total_runs and TotalRuns are ordinary names in two different styles.

  7. Question 7 of 13 Following the Google C++ Style Guide, what would a function that reads the runs be called?

    Choose one answer.

    Show the answer: Question 7 of 13

    Answer: ReadRuns

    The guides disagree: snake_case in the standard library, PascalCase for functions in Google's guide, camelCase in LLVM's. Whichever a project picks, use it everywhere.

  8. Question 8 of 13 Which command rewrites main.cpp in place, in the project's style?

    Choose one answer.

    Show the answer: Question 8 of 13

    Answer: clang-format -i main.cpp

    clang-format -i rewrites the file in place, --dry-run --Werror checks it, and --dump-config writes a complete style file to start from.

  9. Question 9 of 13 How did the two presets write the parameter of Total in messy.cpp?

    Choose one answer.

    Show the answer: Question 9 of 13

    Answer: const std::vector<int> &v with --style=llvm, const std::vector<int>& v with --style=google

    --style=llvm printed const std::vector<int> &v and put the body of the if on its own line; --style=google printed const std::vector<int>& v and kept if (x > 0) t += x; on one line.

  10. Question 10 of 13 A program with using namespace std; and a global variable named count fails with "reference to 'count' is ambiguous", although it includes only <iostream>. Why?

    Choose one answer.

    Show the answer: Question 10 of 13

    Answer: <iostream> brings in std::count from the algorithms library, and the directive makes it visible as count

    Both standard libraries' <iostream> include parts of the algorithms library, so std::count is declared. The using-directive makes every std name usable without std::, and the two counts collide. Writing std:: names or choosing a more specific name avoids it.

  11. Question 11 of 13 Which way of using names from std does this track follow?

    Choose one answer.

    Show the answer: Question 11 of 13

    Answer: It writes std:: names, such as std::cout

    There are three fixes: write std:: names, name the few things you use with using std::cout;, or keep your own names specific. The first is the rule this track follows.

  12. Question 12 of 13 What should a comment say, by the Core Guidelines' rules NL.1 and NL.2?

    Choose one answer.

    Show the answer: Question 12 of 13

    Answer: The intent, and what the code cannot state clearly itself

    A comment that repeats the code goes stale and helps nobody. A useful one says what the code cannot: why it does something, what it assumes, or what the reader would otherwise get wrong.

  13. Question 13 of 13 Which change helps a reader most with int t = 0; // the total of the runs?

    Choose one answer.

    Show the answer: Question 13 of 13

    Answer: Rename t to total and delete the comment

    Good names make most other comments unnecessary. Keep comments for what a name cannot say: why, what is assumed, and what a reader would get wrong.

Interview questions

Why should a header never contain using namespace std;? (warm-up)

A header is copied into every file that includes it, so a using-directive in it applies to all of those files, including ones written by people who never asked for it and cannot remove it. Every name of std then competes with their own names: a global variable called count, distance or size becomes ambiguous with std::count, std::distance or std::size, and the error appears in their code, far from the header that caused it. Which names clash also depends on what the standard library’s headers happen to include, so code can break after a compiler upgrade. Rule SF.7 of the C++ Core Guidelines rules out a global using-directive in a header for this reason. In a header, write std:: names; in a source file, prefer them too, or a using std::name; declaration.

Expect the interviewer to dig further. Two follow-up questions come next: choose your answer, and the feedback tells you what each choice gets right and what it leaves out.

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 An interviewer follows up: the directive sits in scores.h, which ten files include. One of them, written by another team, has a global count. Where does the error appear, and where is it fixed?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: In the other team's file, which never wrote the directive; it is fixed by taking the directive out of scores.h

    A using-directive in a header applies to every file that includes it, also to files whose authors never asked for it and cannot remove it. The error appears in their code, far from the header that caused it.

  2. Question 2 of 2 And then: which names clash depends on what the standard library's headers happen to include. What does that mean for a file with using namespace std; that compiles today?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It can stop compiling after a compiler or library upgrade, with no change to the file

    A program can compile today and break when the next version of a library includes one header more. Writing std:: names, or naming the few you need as in using std::cout;, keeps the file safe from whatever the headers pull in.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    After a compiler upgrade, a 50,000-line codebase fails with "reference to 'size' is ambiguous" in twenty files. Every file starts with using namespace std;. Explain the cause and plan a fix that does not stop the team for a week.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    You want to introduce clang-format to a 200-file repository that five people change every day. How do you roll it out without wrecking git blame or causing a week of merge conflicts, and how do you keep the code formatted afterwards?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Lay out a file as: purpose comment, includes, constants, declarations, a short main, then the helper functions.
  • A name declared in a block ends at the block’s closing brace; declare each name in the smallest scope that needs it.
  • Use one naming style everywhere; this track uses the standard library’s snake_case. Never begin a name with an underscore and a capital letter, or use a double underscore.
  • clang-format sets the layout from a .clang-format file: -i to rewrite, --dry-run --Werror to check in CI. It fixes layout, not names.
  • using namespace std; made a global count ambiguous with std::count with only <iostream> included; write std:: names, and never put the directive in a header.
  • Comments should say why, not repeat what the code says.

Terms in this lesson

namespace
A named scope that groups names so that they cannot collide: the standard library's names are in namespace std, so std::count and a program's own count are two different names.
scope
The part of a program in which a name can be used. A name declared inside a block, the code between a pair of braces, can be used from its declaration up to the block's closing brace.
using-directive
A line such as using namespace std; that makes every name of a namespace usable without its prefix, from that line to the end of the scope it is written in. In a header, it reaches every file that includes the header.

Corrections

  • LLVM's coding standards are now described as they read: a rule against using namespace std, in headers above all, rather than a claim that LLVM's code never uses it.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.