toupper() function in C++

In this guide, you will learn what is toupper() function is in C++ programming and how to use it with an example.

1. toupper() Function Overview

The toupper() function, part of the C++ <cctype> library, converts a given character to its uppercase variant if it is a lowercase letter (a to z). If the input character is either already uppercase or isn't an alphabetic letter, the character is returned as is.

Signature:

int toupper(int ch);

Parameters:

- ch: The character to be converted. While it's technically of type int, it generally corresponds to the ASCII value of the character.

2. Source Code Example

#include <iostream>
#include <cctype>

int main() {
    char ch1 = 'a';
    char ch2 = 'Z';

    std::cout << "Uppercase of ch1 (" << ch1 << ") is: " << static_cast<char>(toupper(ch1)) << std::endl;
    std::cout << "Uppercase of ch2 (" << ch2 << ") is: " << static_cast<char>(toupper(ch2)) << std::endl;

    return 0;
}

Output:

Uppercase of ch1 (a) is: A
Uppercase of ch2 (Z) is: Z

3. Explanation

In the provided example, the toupper() function is utilized to convert characters to their uppercase versions. 

For ch1, with the value 'a', the function returns the uppercase variant 'A'. 

For ch2, which is already an uppercase 'Z', the function returns the character as it is.


Comments