Skip to main content
v2026.11,986 entries · CC-BY 4.0

LaTeX Programming: Counters, ifthen and expl3 Explained

LaTeX programming explained: counters, ifthen conditionals and loops, and expl3 functions, with documented commands, scoping rules and error fixes.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

LaTeX programming means using the macro language underneath a LaTeX document to store values in counters, make decisions with conditionals, repeat work in loops and define your own commands. In practice you meet it at three levels: the counter commands built into LaTeX, the ifthen package for conditionals and a simple loop, and the expl3 programming layer maintained by the LaTeX Project, which gives integers, booleans, sequences and a systematic naming scheme.

What LaTeX programming is used for in research

Researchers use LaTeX programming to make a manuscript, thesis or report compute things instead of hard-coding them: numbering that follows your own rules, text that appears only when a condition holds, and repeated structures generated from a short definition. This page is about the programming language itself. If you want to typeset source code or pseudocode, see the separate guides on code listings in LaTeX and algorithms in LaTeX; for defining shortcut commands, see how to define commands with newcommand.

The reference documentation for the modern layer, The LaTeX3 Interfaces, describes the expl3 programming environment as a set of modules that give systematic names to functions and variables and specify the argument types of each function. It also states that TeX and e-TeX primitives are all given new names and that direct use of primitives is neither required nor encouraged. The same document describes the expl3 modules as defining an independent low-level LaTeX3 programming language designed to be loaded on top of LaTeX2e.

The LaTeX Project’s own LaTeX3 page records the direction of travel: its 2020 entry is titled “Integration of the L3 programming layer into the LaTeX format”, and the project describes a plan to modernise LaTeX rather than release a separate LaTeX3 format, keeping compatibility with existing documents. For a researcher this means the older and newer techniques below coexist, and you choose between them by the size of the job.

Three levels at a glance

  • Counters. Integer variables with a small set of commands for creating, setting, adding to and printing them.
  • ifthen. A separate package whose CTAN entry describes \ifthenelse as able to use “a wide array of tests” and \whiledo as “a simple loop command”.
  • expl3. A full programming layer with typed variables, conditionals, loops, floating-point functions and regular expressions modules.

How to install or access LaTeX programming tools

There is nothing separate to buy or install for the counter commands: they work in any LaTeX document. The other two levels ship with the common distributions. The CTAN entry for ifthen lists it under the LaTeX Project Public License 1.3c and notes that it is included in TeX Live (as latex) and MiKTeX (as ltxbase); the CTAN entry for expl3 lists the same licence and the same two distributions, and describes expl3 as the wrapper package for the LaTeX3 kernel distribution (l3kernel).

The Overleaf guide Learn LaTeX in 30 minutes gives the two ways to begin: create a new .tex file on your own computer, or create a new Overleaf project. It describes TeX Live as a yearly distribution you can use for a local setup, and notes that Overleaf uses a subset of TeX Live, so some packages found on CTAN may be unavailable there. Packages are loaded with \usepackage, and ifthen always needs it, because it is a separate package. For details on running the compiler locally or online, see the guide on compiling LaTeX documents and the explainer on what Overleaf is.

Check the version your installation provides before relying on a function. At the time recorded in the CTAN entries, ifthen was at version 1.1e (2026-06-01) and the expl3 distribution at version 2026-09-09; the interface documentation was released on the same date.

How to program in LaTeX step by step

The steps below move from the simplest tool to the most capable one. Every command shown is taken from the documentation cited in the Sources list.

Step 1: create a file and a counter

  1. Create a new .tex file locally or a new Overleaf project, as described in Learn LaTeX in 30 minutes.
  2. Create a counter with \newcounter{chapterCount}. A new counter starts at 0. If a counter with that name already exists, LaTeX reports that it is already defined.
  3. Set it with \setcounter{chapterCount}{5}. The value can be negative.
  4. Add to it with \addtocounter{chapterCount}{3}, or add one with \stepcounter{chapterCount}.
  5. Print it with \arabic{chapterCount}. After the commands in steps 2 to 4 the Overleaf example prints 9.

Step 2: pass a value between counters

The command \value{c} returns the number held by a counter so that other commands can use it; it does not print anything. The Overleaf counters page shows copying one counter into another with \setcounter{copy}{\value{chapterCount}}. Using value alone at the top level of the document produces the error “Missing number, treated as zero.”

Step 3: add a conditional or a loop with ifthen

Load the package in the preamble with \usepackage{ifthen}. It then provides ifthenelse for conditional text and whiledo for a simple loop, according to the CTAN description. Because the exact test syntax is documented in ifthen.pdf, the full syntax is in ifthen.pdf, listed in Sources.

Step 4: switch to expl3 for anything larger

The expl3 syntax is turned on and off with a pair of commands. Inside the pair, names use underscores and colons, and the letters after the colon state the argument types of the function. A minimal block that uses the integer, comparison and loop functions documented in The LaTeX3 Interfaces looks like this:

\ExplSyntaxOn
\int_new:N \l_my_int
\int_set:Nn \l_my_int { 4 }
\int_incr:N \l_my_int
\int_compare:nNnTF { 5 } > { 3 } { yes } { no }
\int_step_inline:nnnn { 1 } { 1 } { 3 } { \int_eval:n { #1 * #1 } }
\ExplSyntaxOff

The functions do the following, as defined in the interface documentation. \int_new:N creates an integer variable, \int_set:Nn assigns an integer expression to it, \int_add:Nn adds an expression and \int_incr:N adds one (\int_decr:N subtracts one). \int_eval:n evaluates an integer expression from left to right, and integer variables used inside it need no \int_use:N. \int_step_inline:nnnn takes an initial value, a step and a final value, evaluates each as an integer expression, and for every value inserts the code with #1 standing for the current value. \int_compare:nNnTF compares two integer expressions with a relation such as > and runs the true or false branch.

In the block above the loop body contains no separator, so the squares of 1, 2 and 3 are typeset one after another with nothing between them: that is a direct consequence of the loop inserting the code once per value, and you add your own separator when you need one.

Step 5: define your own function

Functions are created with \cs_new:Npn followed by the function name, its parameters and the code in braces, with the parameters written #1, #2 and so on. The interface documentation distinguishes three scopes, which matters when a definition sits inside a group such as an environment:

Variant Scope If the name is already defined
\cs_new:Npn Global Error
\cs_set:Npn Current TeX group No error
\cs_gset:Npn Global No error

The same documentation shows a practical use that researchers will recognise: with the siunitx package loaded, a command defined as \NewDocumentCommand { \calcnum } { m } { \num { \fp_to_scientific:n {#1} } } inside an expl3 block lets you write \calcnum { 2 pi * sin ( 2.3 ^ 5 ) } and have the floating-point module evaluate the expression and the number be typeset in scientific notation. That is a compact way to keep a computed value in the source of a paper rather than copying it from a separate calculation.

Choosing the level

Use counters when you only need to number or count. Use ifthen when you need one condition or a short loop and want familiar names. Use expl3 when you need several variables, nested logic, expression evaluation or code you will reuse across documents, because its naming scheme tells you a function’s module and argument types at a glance. If the task is mainly about the engine rather than the macro layer, such as scripting with an embedded language, see the alternatives section below.

How to read the output

Programming output arrives in two places: the typeset PDF and the compilation messages. Counter commands such as \arabic place their result in the PDF; value does not print, which is why using it alone produces the missing-number error. In expl3, expandable functions such as int_eval:n leave their result in the text, so the PDF shows the number. The interface documentation also describes int_show:n, whose documented example for the expression 5 + 4 * 3 - ( 3 + 4 * 5 ) gives -6; the arithmetic is evaluated left to right with the usual operator precedence, so 4 * 3 is 12 and 3 + 4 * 5 is 23, giving 5 + 12 – 23 = -6.

The sorting example in the same document is a good test of reading results: sorting the comma list { 3 , 01 , -2 , 5 , +1 } with an \int_compare:nNnTF comparison gives { -2 , 01 , +1 , 3 , 5 }. Notice that 01 and +1 keep their original written form, because the comparison is numeric while the items are not rewritten. When a result looks wrong, print intermediate values rather than the final one.

Troubleshooting LaTeX programming

The documentation cited here names the errors below. Each row gives the symptom, the cause stated in the source and the fix.

Symptom Cause Fix
Counter reported as already defined \newcounter was used with a name that exists Choose a new name, or change the existing counter with \setcounter
“Missing number, treated as zero.” \value was used at the top level of the document, where it returns a number but does not print Print with \arabic{c}, or use \value only inside another command that expects a number
Error when defining a function \cs_new:Npn is global and errors if the name is already defined Use a new name, or use \cs_set:Npn (group-local) or \cs_gset:Npn (global) when redefinition is intended
Definition disappears after a group ends \cs_set:Npn applies only within the current TeX group Use \cs_gset:Npn when the definition must outlive the group
Conditional package commands are undefined ifthen is a separate package and always needs \usepackage Add \usepackage{ifthen} to the preamble
Package missing on Overleaf Overleaf uses a subset of TeX Live Use a package that Overleaf provides, or compile locally with a full TeX Live

Two habits prevent most of these problems: keep expl3 code between \ExplSyntaxOn and \ExplSyntaxOff so that underscores and colons are read as name characters, and test each definition in a small file before placing it in a long thesis.

Free alternatives to LaTeX programming

The three options below are all free software and all listed on CTAN. The comparison is limited to what each CTAN entry states.

Option What the CTAN entry says Where it ships Licence
ifthen Conditional commands in LaTeX documents; \ifthenelse with a wide array of tests; a simple loop command \whiledo TeX Live (latex), MiKTeX (ltxbase) LPPL 1.3c
expl3 Wrapper package for the LaTeX3 kernel distribution (l3kernel) TeX Live, MiKTeX LPPL 1.3c
LuaTeX An extended version of pdfTeX using Lua as an embedded scripting language TeX Live (luatex), MiKTeX (miktex-luatex-bin-2.9) GPL v2 or later

LuaTeX is the option for people who would rather write logic in a general scripting language than in macros. The related guide on LuaLaTeX covers using it from a LaTeX document. Whichever route you take, the data table below summarises the counter and expl3 integer commands side by side so you can translate between the two styles.

Sources

Data: LaTeX counter commands and their expl3 integer counterparts

Side-by-side list of the LaTeX counter commands documented by Overleaf and the expl3 integer functions documented in The LaTeX3 Interfaces, compiled for one task each: create, set, add, increment, evaluate and loop. Cells marked as not covered mean the cited page does not describe a direct equivalent.

LaTeX counter commands and their expl3 integer counterparts
TaskLaTeX counter commandexpl3 integer function
Create a variable\newcounter{c} (starts at 0; error if the name exists)\int_new:N
Set a value\setcounter{c}{n} (n may be negative)\int_set:Nn \l_tmp_int { 4 }
Add an amount\addtocounter{c}{n}\int_add:Nn
Add one\stepcounter{c}\int_incr:N
Subtract oneNot covered by the cited counters page\int_decr:N
Print or use the value\arabic{c} prints; \value{c} returns the number without printing\int_eval:n evaluates an integer expression left to right
Repeat code over a rangeNot covered by the cited counters page\int_step_inline:nnnn {initial}{step}{final}{code}, with #1 the current value

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about LaTeX Programming: Counters, ifthen and expl3 Explained

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →