Rewrite C Function: isalnum

Last Updated : 10 July, 2022 · 3 min read

articles banner image

Today we are going to take a closer look at isalnum function and it's inner workings in C programming language. For reader's convenience, we have divided this tutorial into 3 parts:

Structure of isalnum.

Declaration: int isalnum(int c);

Return: non-zero value if int c is a digit or an alphabetic value. Otherwise, 0.

Parameter list:
(int c) - the character that is checked to determine the return value.

Header file: <ctype.h>.

1. So, what is isalnum in C?

The isalnum function checks if the passed char value is in alphabet (a-z, A-Z) or is a digit (0-9), and returns an appropriate value of type int indicating the result.

If the argument is in alphabet or is a digit , function isalnum returns a non-zero value.

If the argument is not in alphabet and is not a digit, 0 is returned.

The isalnum function is defined in the <ctype.h> library. This means that in order to use this function we have to include this header file (e.g. #include <ctype.h>).

Example 1: usage of isalnum function in C

# include <stdio.h>
# include <ctype.h>

int main( void )
{
    
printf ( "%d\n", isalnum ( 'a' ));
    
printf ( "%d\n", isalnum ( '5' ));
    
printf ( "%d\n", isalnum ( '+' ));
    
return ( 0 );
}

Possible output:

1
1
0

2. And how to rewrite isalnum function in C?

Consider the lines of code below for a minute:

Example 2: Rewritten isalnum function.

int our_isalnum ( int c )
{
    
if ( ( isalpha (c) ) || ( isdigit (c) ) )
        
return ( 1 );
    
return ( 0 );
}

The our_isalnum function above takes one parameter. Since this parameter c is of int type, arguments of char type (when sent to this function) get implicitly typecasted to according numerical values.

Then we pass this received c variable to isalpha and isdigit functions (On line 3). If any of them return true (that is, a number not equal to zero), our_isalnum returns 1. Otherwise, 0 is returned.

3. Quiz of isalnum knowledge

Quiz : Rewritten isalnum function in C

1What would isalnum function return, if isalnum(';')?

2In which C library is isalnum function defined?

3What would isalnum return, if isalnum(101)?

quiz completed!

Congrats!

Feel free to share your achievement below!