Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
strcspn() in C
Next article icon

C strcmp()

Last Updated : 02 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, strcmp() is a built-in library function used to compare two strings lexicographically. It takes two strings (array of characters) as arguments, compares these two strings lexicographically, and then returns some value as a result.

Let’s take a look at an example:

C
#include <stdio.h> #include <string.h>  int main(){     char* s1 = "Geeks";     char* s2 = "Geeks";      // Printing the return value of the strcmp()     printf("%d", strcmp(s1, s2));      return 0; } 

Output
0

Explanation: In this code, two strings, s1 and s2, are declared with the same value “Geeks“. The strcmp() function compares these two strings and returns 0 since they are identical.

This article covers the syntax of count() function, its working, and common usage with examples.

Table of Content

  • Syntax of strcmp()
  • How strcmp() works?
  • Examples of strcmp() in C
    • Find Identical Strings
    • Find Lexicographically Greater String
    • Sort the Array of Strings

Syntax of strcmp()

The strcmp() function is defined inside the <string.h> header file as:

strcmp(s1, s2);

Parameters:

  • s1: First string.
  • s2: Second string.

Return Value:

The strcmp() function returns three different values after the comparison of the two strings which are as follows:

  • Zero (0): It returns zero when all of the characters at given indexes in both strings are the same.
  • Greater than Zero ( > 0 ): Returns a value greater than zero is returned when the first not-matching character in s1 has a greater ASCII value than the corresponding character in s2.
  • Lesser than Zero ( < 0 ): Returns a value less than zero is returned when the first not-matching character in s1 has a lesser ASCII value than the corresponding character in s2.

How strcmp() works?

C strcmp() function works by comparing the two strings lexicographically. It means that it compares the ASCII value of each character till the non-matching value is found or the NULL character is found. The working of the C strcmp() function can be described as follows:

1. It starts with comparing the ASCII values of the first characters of both strings.

2. If the first characters in both strings are equal, then this function will check the second character, if they are also equal, then it will check the third, and so on till the first unmatched character is found or the NULL character is found.

3. If a NULL character is found, the function returns zero as both strings will be the same.

compare-similar-strings-using-strcmp

4. If a non-matching character is found,

  • If the ASCII value of the character of the first string is greater than that of the second string, then the positive difference ( > 0) between their ASCII values is returned.
compare-larger-string-with-smaller-string-using-strcmp
  • If the ASCII value of the character of the first string is less than that of the second string, then the negative difference ( < 0) between their ASCII values is returned.
compare-smaller-string-with-larger-string-using-strcmp

All of these three cases are demonstrated in the below examples.

Examples of strcmp() in C

The below examples demonstrate the behaviour of strcmp() in C programs:

Find Identical Strings

C
#include<stdio.h> #include<string.h>  int main() {          char s1[] = "g f g";     char s2[] = "g f g";          // Using strcmp() to compare s2 and s2     int res = strcmp(s1, s2);          if (res == 0)         printf("Equal");     else         printf("Unequal");        return 0; } 

Output
Equal

Explanation: In this code, strcmp is used to compare two strings, s1 and s2. Since both strings are identical (“g f g”), strcmp returns 0, indicating the strings are equal. The program then prints “Equal“. If the strings were different, strcmp would return a non-zero value, and the program would print “Unequal“.

Find Lexicographically Greater String

C
#include<stdio.h> #include<string.h> int main() {     // z has greater ASCII value than g     char first_str[] = "zfz";     char second_str[] = "gfg";          int res = strcmp(first_str, second_str);          if (res==0)         printf("Equal");     else         printf("Unequal");          return 0; } 

Output
Unequal

Explanation: In this code, strcmp compares the two strings first_str (“zfz”) and second_str (“gfg”). Since ‘z’ has a greater ASCII value than ‘g’, strcmp returns a positive value, indicating the strings are unequal. The program prints “Unequal” because of the lexicographical comparison based on ASCII values.

Sort the Array of Strings

As strcmp() compare two strings, it can be used to sort the array of strings in the desired order by using it as a comparator function in qsort().

C
#include <stdio.h>  #include <stdlib.h>  #include <string.h>   int comp(const void* a, const void* b)  {   	// Using strcmp() for comparing two strings 	return strcmp(*(const char**)a, *(const char**)b);  }  int main()  {  	const char* arr[] = { "Rahul", "Vikas", "Mukesh" };   	int n = sizeof(arr) / sizeof(arr[0]);   	// Sort the given arr  	qsort(arr, n, sizeof(arr[0]), comp);   	// Print the sorted arr 	for (int i = 0; i < n; i++)  		printf("%s\n", arr[i]);  	return 0;  }  

Output
Mukesh Rahul Vikas 


Next Article
strcspn() in C
author
kartik
Improve
Article Tags :
  • C Language
  • C-String

Similar Reads

  • strcpy() in C
    In C, strcpy() is a built-in function used to copy one string into another. It is a part of the C standard strings library, which provides various functions to manipulate strings efficiently. Let's take a look at an example: [GFGTABS] C #include <stdio.h> #include <string.h> int main() {
    3 min read
  • strcspn() in C
    The C library function strcspn() calculates the length of the number of characters before the 1st occurrence of character present in both the string. Syntax : strcspn(const char *str1, const char *str2) Parameters: str1 : The Target string in which search has to be made. str2 : Argument string conta
    3 min read
  • strchr in C
    The strchr() function in C is a predefined function in the <string.h> library. It is used to find the first occurrence of a character in a string. It checks whether the given character is present in the given string or not, if the character is found it returns the pointer to it otherwise it re
    4 min read
  • strcat() in C
    C strcat() function appends the string pointed to by src to the end of the string pointed to by dest. It will append a copy of the source string in the destination string. plus a terminating Null character. The initial character of the string(src) overwrites the Null-character present at the end of
    2 min read
  • strrchr() in C
    The strrchr() function in C locates the last occurrence of a character in a string and returns a pointer to it. It is a standard library function defined inside <string.h> header file. Syntax : char* strrchr( char* str, int chr ); Parameter: str: specifies the pointer to the null-terminated st
    2 min read
  • strcmpi() function in C
    The strcmpi() function is a built-in function in C and is defined in the "string.h" header file. The strcmpi() function is same as that of the strcmp() function but the only difference is that strcmpi() function is not case sensitive and on the other hand strcmp() function is the case sensitive.  Sy
    2 min read
  • memcmp() in C
    In C, memcmp() is a built-in function used to compare the given number of bytes of data pointed by two pointers passed as arguments. It returns an integer indicating whether the first memory block is less than, equal to, or greater than the second. Example: [GFGTABS] C #include <stdio.h> #incl
    4 min read
  • Strings in C
    A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is work as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. DeclarationDeclaring a string in C
    5 min read
  • system() in C/C++
    The system() function is used to invoke an operating system command from a C/C++ program. For example, we can call system("dir") on Windows and system("ls") in a Unix-like environment to list the contents of a directory. It is a standard library function defined in <stdlib.h> header in C and
    6 min read
  • scanf in C
    In C, scanf() is a function is used to read data from stdin (standard input stream i.e. usually keyboard) and stores the result into the given arguments. It is defined in the <stdio.h> header file. Example: [GFGTABS] C #include <stdio.h> int main() { int n; // Reading an integer input sc
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences