Using getchar_unlocked() function in C/C++

In this tutorial let us learn what is the getchar_unlocked function, how to use this function using C/C++, and what are its advantages. Before going into the topic, let us see some similar functions like getchar and getc.

getc()

It reads a single value from the given stream and returns the ASCII value of that character.

#include <stdio.h> 
int main() 
{ 
   char a;
   printf("Enter the chracter : ");
   a=getc();
   printf("\nOutput : %c",a); 
   return 0; 
}

Output:

Enter the character : g 
Output : g

getchar()

The difference between getc() and getchar() is that getc() can read from any input stream, but getchar() reads from standard input.

#include <stdio.h> 
int main() 
{ 
   char a;
   printf("Enter a character : ");
   a=getchar();
   printf("\n%c",a); 
   return 0; 
}

Output:

Enter the character : g

 g

Now that we have seen some similar functions let us dive into the topic.

getchar_unlocked() in C++

The getchar_unlocked function is not thread-safe.

getchar_unlocked function is faster than the getchar function.

Warning: be careful with large I/O in certain languages.

All the overheads of mutual exclusion are avoided as it is not thread-safe.

Example:

#include<iostream>
int main()
{
    char a;
    printf(" Enter a character : ");
    a=getchar_unlocked();
    printf("\n The entered character is : %c",a);
    return 0;
}

Output: 

 Enter a character : a                                                                                                                        
 The entered character is : a

#include<stdio.h>
int main()
{
    char a;
    printf(" Enter a character : ");
    a=getchar_unlocked();
    printf("\n The entered character is : %c",a);
    return 0;
}

Output:

 Enter a character : abcd                                                                                                                        

 The entered character is : a

With this note, I want to end this tutorial. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *