Using toupper() in C - A Practical Guide With Examples

In this article, we’ll take a look at how we can use the toupper() function in C.

This is a very straightforward function, which converts a character to upper case. Let’s quickly look at some examples of this function.


Basic Syntax of toupper() in C

This function, similar to the isdigit() function, is present in the <ctype.h> header file, so we must first include this file.

This function takes in a single character as argument, and returns an integer.

Here, notice that the argument type is an int. This is because characters can be type-cast to integers for the function to be able to work on the ASCII values.

If the character is a lower case letter, like ‘a’, ‘b’, the toupper() function will return convert this to the corresponding upper case letter, and return that ASCII value.

Otherwise, it will simply return the same upper-case string. Observe that this could happen if the input parameter could not be converted to upper case!

Now, let’s look at a simple example in C.


Using the toupper() function – An example

The below program will take a string as input, and will convert all the lower-cased letters to uppercase

For example, if we pass the string “JOUrnalDev” as input, we’ll get the output as “JOURNALDEV”, which only consists of upper-case letters.

Notice that this also includes all the upper case characters in the original string!

Output

Indeed, as you can see, the output string only consists of upper-case letters!

Undefined Behavior with certain inputs

While the toupper() function tries it’s best to convert a value to upper-case, sometimes, it may not be possible.

According to the Linux standard, the behavior is undefined if the value is beyond the limits of an unsigned character value (256), or if the value is EOF.

Due to this, always be careful and place a check on your input, before passing it to toupper()!


Conclusion

In this article, we saw how we could use the toupper() function in C to convert a character to upper-case.

References


By admin

Leave a Reply

%d bloggers like this: