Lably
Skip to content

Const

Type qualifier denoting the data as being read-only

  • 33 min read
  • 11 chapters

Related on Lably

Through Data type, Constant (computer programming) and JavaScript

Introduction

When applied in an object declaration, it indicates that the object is a constant: its value may not be changed, unlike a variable. This basic use – to declare constants – has parallels in many other languages.

However, unlike in other languages, in the C family of languages the const is part of the type, not part of the object. For example, in C, const int x = 1; declares an object x of const int type – the const is part of the type, as if it were parsed "(const int) x" – while in Ada, X : constant INTEGER := 1_ declares a constant (a kind of object) X of INTEGER type: the constant is part of the object, but not part of the type.

This has two subtle results. Firstly, const can be applied to parts of a more complex type – for example, const int* const x; declares a constant pointer to a constant integer, while const int* x; declares a variable pointer to a constant integer, and int* const x; declares a constant pointer to a variable integer. Secondly, because const is part of the type, it must match as part of type-checking. For example, the following code is invalid:

<span id="mwVg"></span><span class="kt" id="mwVw">void</span><span class="w" id="mwWA"> </span><span class="nf" id="mwWQ">f</span><span class="p" id="mwWg">(</span><span class="kt" id="mwWw">int</span><span class="o" id="mwXA">&</span><span class="w" id="mwXQ"> </span><span class="n" id="mwXg">x</span><span class="p" id="mwXw">);</span> <span class="c1" id="mwYA">// ...</span> <span class="k" id="mwYQ">const</span><span class="w" id="mwYg"> </span><span class="kt" id="mwYw">int</span><span class="w" id="mwZA"> </span><span class="n" id="mwZQ">i</span><span class="p" id="mwZg">;</span> <span class="n" id="mwZw">f</span><span class="p" id="mwaA">(</span><span class="n" id="mwaQ">i</span><span class="p" id="mwag">);</span>

because the argument to f must be a variable integer, but i is a constant integer. This matching is a form of program correctness, and is known as const-correctness. This allows a form of programming by contract, where functions specify as part of their type signature whether they modify their arguments or not, and whether their return value is modifiable or not. This type-checking is primarily of interest in pointers and references – not basic value types like integers – but also for composite data types or templated types such as containers. It is concealed by the fact that the const can often be omitted, due to type coercion (implicit type conversion) and C being call-by-value (C++ and D are either call-by-value or call-by-reference).

Sign in to keep reading

10 more chapters are free with a Lably account.

More in Computing and communication