The Wayback Machine - https://web.archive.org/web/20241006171652/https://www.geeksforgeeks.org/getchar_unlocked-faster-input-cc-competitive-programming/
Open In App

getchar_unlocked() – Faster Input in C/C++ For Competitive Programming

Last Updated : 08 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile().

Syntax:

int getchar_unlocked(void);

Example:

Input: g

C++




// C++ program to demonstrate
// working of getchar_unlocked()
#include <iostream>
using namespace std;
 
int main()
{
    // Syntax is same as getchar()
    char c = getchar_unlocked();
 
    cout << "Entered character is " << c;
 
    return 0;
}
 
// This code is contributed by SUBHAMSINGH10.


C




// C program to demonstrate
// working of getchar_unlocked()
#include <stdio.h>
int main()
{
    // Syntax is same as getchar()
    char c = getchar_unlocked();
 
    printf("Entered character is %c", c);
 
    return 0;
}


Output

Entered character is g 

Following are Some Important Points: 

  1. Since it is not thread-safe, all overheads of mutual exclusion are avoided and it is faster than getchar().
  2. Can be especially useful for competitive programming problems with “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”.
  3. There is no issue with using getchar_unlocked() even in a multithreaded environment as long as the thread using it is the only thread accessing file object
  4. One more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows-based compilers.
  5. It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all.
  6. Similarly, there are getc_unlocked() putc_unlocked(), and putchar_unlocked() which are non-thread-safe versions of getc(), putc() and putchar() respectively.

Example:

Input: g

C++




// C++ program to demonstrate
// working of putchar_unlocked()
#include <iostream>
using namespace std;
int main()
{
    // Syntax is same as getchar()
    char c = getchar_unlocked();
 
    putchar_unlocked(c);
 
    return 0;
}
 
//This code is contributed by Shubham Singh


C




// C program to demonstrate
// working of putchar_unlocked()
#include <stdio.h>
int main()
{
    // Syntax is same as getchar()
    char c = getchar_unlocked();
 
    putchar_unlocked(c);
 
    return 0;
}


Output

g

As an exercise, the readers may try solutions given here with getchar_unlocked() and compare performance with getchar(). 



Similar Reads

Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Python Input Methods for Competitive Programming
Python is an amazingly user-friendly language with the only flaw of being slow. In comparison to C, C++, and Java, it is quite slower. In online coding platforms, if the C/C++ limit provided is x. Usually, in Java time provided is 2x, and in Python, it's 5x. To improve the speed of code execution for input/output intensive problems, languages have
6 min read
Input/Output from external file in C/C++, Java and Python for Competitive Programming
In Competitive Programming, most of the time we need to enter input for checking our code manually. But it would become cumbersome if we have a questions like Graphs, strings, or bulky entry of input data because it will definitely time out or the chances of typing incorrect data would be increased. We can easily get rid of problem by simply saving
4 min read
Input/Output from external file in C/C++, Java and Python for Competitive Programming | Set 2
Prerequisites : Input/Output from external file in C/C++, Java and Python for Competitive Programming In above post,  we saw a way to have standard input/output from external file using file handling. In this post, we will see a very easy way to do this. Here we will compile and run our code from terminal or cmd using  input and output streams. Win
3 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 min read
Why are elementwise additions much faster in separate loops than in a combined loop?
When adding more than 2 arrays, separate loops for adding elements step by step prove to give a better performance than adding the elements in a single loop. To Test the above statement, two code blocks add the 4 array elements namely array a with b and c with d. The first code block uses a combined loop to add them while the second block uses two
3 min read
Which will be faster while(1) or while(2)?
In most Programming Languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The boolean condition is either true or false. while(1) & while(2) It is an infinite loop that will run till a break statement is issued explicitly. Neither while(1) nor while(2) but any integer whic
2 min read
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm
Given a graph G consisting of nodes valued [0, N - 1], a source S, and an array Edges[][3] of type {u, v, w} that denotes that there is a directed edge between node u and v with weight w, the task is to check if there exists a negative cycle from the given source. If found to be true, then print "Yes". Otherwise, print "No". A negative cycle is a c
11 min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
GFact | Why s.lower_bound(x) is faster than lower_bound(s.begin(), s.end(), x) in C++ STL?
Have you ever got TLE on solving a question using function lower_bound (s.begin(), s.end(), x) and when you use s.lower_bound(x) it runs just fine (here s is a Data structure and x is the value we are searching for) !! If "Yes" then why this happens? Well, we are going to find out this in the following article, but before that let's know about the
4 min read
Why is C considered faster than other languages ?
You might have came across these statements, C is more optimised or performance of C is better than higher languages, so I'll be discussing the reasons for this hypothesis. First let's list out functionalities which are provided by languages like Java and not C : Array index bound checkingUninitialized variable values checkingCheck for memory leaks
2 min read
Why is it faster to process sorted array than an unsorted array ?
Here is a C++ and java code that illustrates that sorting the data miraculously makes the code faster than the unsorted version. Let's try out sample C++ and java programs to understand the problem statement better. Implementation: C/C++ Code // CPP program to demonstrate processing // time of sorted and unsorted array #include <iostream> #in
6 min read
Writing code faster in C++ STL
You are wondering some time coder write his code in 2 min or less how? No kidding! Although this tip may not be very useful for competitions such as ICPC or IOI. But there are recent ICPCs ranks where rank i and rank i + 1 are just separated by few minutes. When you can solve the same number of problems as your competitor, it is now down to coding
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
How to read Competitive Programming Questions?
Competitive Programming is considered as a sport in the field of computer science. The culture of this sport is growing day by day and a lot of people are also considering this as a career choice. So, to help the participants with improving their efficiency in this sport, in this post, we have tried to cover all possible things, needed to keep in m
5 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Importance of Testing In Competitive Programming
Many times while solving problems, we face issues like time limit exceeds, wrong solution, runtime error, and memory limit exceeds because after designing algorithm we don't test algorithm efficiency, correctness, time complexity and running the algorithm on a large set of inputs for testing purpose. This is where stress testing comes for rescue. S
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
5 Best Languages for Competitive Programming
Needless to say, Competitive Programming is one of the most crucial and popular aspects of a programmer's journey. Though, all the programmers are strongly recommended to participate in such coding challenges to enhance their coding skills and to get various ravishing prizes, rewards, and other career opportunities. Meanwhile, there's a question th
5 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
How to get started with Competitive Programming in JavaScript
Competitive programming is a popular activity among programmers looking to enhance their problem-solving skills and algorithmic thinking. JavaScript is a wonderful language for competitive programming because of how simple it is to use, how powerful its libraries are, and how quickly it can prototype ideas. JavaScript is a great option for programm
5 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
Points to focus on while doing Competitive Programming
Competitive Programming is vital for one’s development in the coding field. This article is going to discuss some basics points one should keep in mind while competing. Make a list of functions to perform tasks that are encountered frequently in questions and add them to your code in the form of a template. This saves time during contests and helps
5 min read
How to Use int as long long int for Competitive Programming?
Most of the time, input constraints in Competitive programming questions are bigger than the limits of int. Therefore, there is a need to use long int or even long long int. Here let us take two cases so that if a naive user writes correct logic still input is not getting accepted can get to know where the rectification is required. Case 1: Big int
3 min read
Practice Tags :