cstdlib in C++ – Explained

Dori Exterman
Dori Exterman reading time: 6 minutes
September 14, 2021

What Is cstdlib in C++?

cstdlib in C++ example

The C++ Standard Library header file (cstdlib in C++) is the header for one of the most widely used libraries by programmers of the language. This header defines a collection of functions and macros to facilitate efficient, high-performing, standardized C++ code across teams and platforms.

C++ is a popular programming language and one of the initial reasons for its rise in popularity was compatibility with C, which was a popular and well-established language at the time, and in fact, still is. This compatibility not only meant that it was easier for programmers to adapt but, perhaps more importantly, C++ developers were able to take advantage of pre-existing C code.

Rather than recreate everything from the core functions onward, programmers were able to re-use mature code blocks during a reasonably-paced transition to C++. Specifically, they were able to use the C Standard library header, stdlib.h. Fast-forward to today, cstdlib in C++ is the enhanced C++ version of the original <stdlib.h>.

cstdlib in C++ vs stdlib.h

The C Standard Library Header, <stdlib.h>, offers C programmers reliable and efficient functions for dynamic memory allocation, conversion between datatypes, pseudo-random number generation,  process control, searching and sorting, math, and multibyte or wide characters. In addition to these common routines, oft-used constants exist to promote code standardization across organizations and platforms.

Headers and Namespaces

In the original C++ specification, C++98, it stated that to correctly use functions that were inherited from the C library was by using a <c –name–> header. For example, in a traditional C program, one might include “string.h”, whereas, in C++, an identical project would include <cstring>. Furthermore, with the advent of namespaces, newly-written C++ library functions were no longer to be defined in the global, unqualified namespace. Rather, they would be declared only in the standard namespace, std.

Moving forward, using cstdlib for C++ implies a guarantee that everything included in <stdlib.h> is declared in the std namespace. As such, when developers want to use functions in the Standard Library, they have to be qualified. This can be done explicitly, or with the using directive, as in the following example:

Example of using std shared_ptr

Figure 1: Example of using std::shared_ptr as part of a double-linked list

In the left column, the unqualified use of shared_ptr<> reports an error because the declaration is not in the global namespace. In the middle column, the namespace is explicitly declared, pointing to where the compiler can find it. In the rightmost column, the using namespace std directive directs the compiler to std to search for functions that do not exist inside the local or global scopes. It is to be noted that the third (rightmost) option is considered a bad practice. Another option not seen above is adding just shared_ptr with using std::shared_ptr directive.

Additional functions

The cstdlib in C++ library contains a superset of the traditional C functions, macros, and datatypes. An example of this is the set of absolute value (abs) functions that are declared. In stdlib.h, C defines the functions required to calculate the absolute values (abs) of an integer, long, or long long value. However, there is no provision for obtaining the absolute value of a float, double, or long double. These types are instead declared in math.h, which is another oft-used C header.

Absolute value datatype Function C header
Integer int abs(int x) stdlib.h
Long integer long labs(long x) stdlib.h
Long long integer long long llabs(long long x) stdlib.h
Float float fabsf(float x) math.h
Double double fabs(double x) math.h
Long double long double fabsl(long double x) math.h

Figure 2: Absolute value functions in the C Standard Library

The relevant overrides for abs() within the cstdlib in C++ header cover all of the above cases.

What’s Included?

The cstdlib in C++ header includes several member functions, datatypes, and constant values. The following tables describe what functions are defined by the header file.

Conversion Functions Description or Example
atof Convert a string into a double. Note: The return result is NOT a float.
atoi Converts a string into an integer.
atol Converts a string into a long
The following functions are more robust alternatives to those above
strtod Converts a string into a double.
strtol Converts a string into a long integer.
stltoul Converts a string into an unsigned long integer.
strtoll Converts a string into a long long integer.
strtoull Converts a string into an unsigned long long integer.

Figure 3: Conversion functions

 

Random numbers Description or Example
rand Generates an pseudo-random integer
random A non-standard C integer-returning function (provided by POSIX)
srand Sets the random number generator’s seed value
srandom Sets the random number generator’s seed (non-standard C, POSIX)

Figure 4: Random number-related functions

 

Memory Allocation Description or Example
malloc Allocate memory from the heap (specify entire block size)
calloc Allocate memory from the heap (specify size and count; initialize memory)
realloc Adjust the size of memory that has already been allocated
free De-allocate memory

Figure 5: Dynamic memory allocation functions

 

Searching and Sorting Description or Example
bsearch Perform a binary searching on an array
qsort Sort an array using Quick Sort

Figure 6: Searching and sorting functions

 

Math Functions Description or Example
abs Calculate the absolute value of an integer
labs Calculate the absolute value of a long integer
div Perform integer division with quotient and remainder returned as the result
ldiv Long integer division with quotient and remainder returned in the result

Figure 7: Mathematical functions

 

Multibyte / Wide Character Functions Description or Example
mblen Return the size of a multibyte character
mbtowc Convert a multibyte character to a wide character
wctomb Convert a wide character to a multibyte character
mbstowcs Convert sequence of multibyte characters to a sequence of wide characters
wcstombs Convert sequence of wide characters to a sequence of multibyte characters

Figure 8: Functions for working with multibyte and wide characters

Constants and Macros

The cstdlib in C++ library contains a variety of macros and constants to assist with the standardization of C++ development and code bases. An example of this is the constant values used to return from the main function, as follows:

EXIT_SUCCESS

The EXIT_SUCCESS constant can be used as a return value from the main function that the calling framework will interpret as successful execution. Although the value zero also denotes a successful execution of the program, EXIT_SUCCESS is implementation-specific.

EXIT_FAILURE

The EXIT_FAILURE constant is also used as a return value from the main function. However, it indicates to the calling framework that the execution failed, perhaps with a critical operating-system-level error.

Examples of macros used to return from the main function

Figure 11: Examples of macros used to return from the main function

Other examples of constant values defined by cstdlib in C++ are NULL, which defines a null pointer constant, RAND_MAX, which is the maximum possible value generated by the rand command,  and MB_CUR_MAX, which represents the maximum number of bytes in a multibyte character for the current locale.

In Conclusion…

The header of the general-purpose standard library for C++, also known as cstdlib in C++, defines a core set of functions used for data type conversion, pseudo-random number generation, memory allocation, searching, sorting, mathematics, and dealing with wide or multibyte characters. It also contains a variety of useful macros in the form of constant values. In many cases C++ programmers use types, functions or constants, that come from cstdlib, without having to include this header, as it is being included by other headers that they are using. Not being aware where some types and utilities come from may later lead to annoying compilation errors, when some previously included header is removed and some constatnt is surprisingly not recognized. Knowing that cstlib might be required can save some time in such cases.

speed up c++

Dori Exterman
Dori Exterman reading time: 6 minutes minutes September 14, 2021
September 14, 2021

Table of Contents

Related Posts

6 minutes 8 Reasons Why You Need Build Observability

Read More  

6 minutes These 4 advantages of caching are a game-changer for development projects

Read More  

6 minutes What Level of Build Observability Is Right for You?

Read More