The strcmp() function in C++ compares two null-terminating strings (C-strings). The comparison is done lexicographically. It is defined in the cstring header file.
Example
strcmp() Syntax
The syntax of strcmp() is:
strcmp(const char* lhs, const char* rhs);
Here,
- lhs stands for left hand side
- rhs stands for right hand side
strcmp() Parameters
The strcmp() function takes the following parameters:
- lhs - pointer to the C-string that needs to be compared
- rhs - pointer to the C-string that needs to be compared
strcmp() Return Value
The strcmp() function returns:
- a positive value if the first differing character in lhs is greater than the corresponding character in rhs.
- a negative value if the first differing character in lhs is less than the corresponding character in rhs.
- 0 if lhs and rhs are equal.
strcmp() Prototype
The prototype of strcmp() as defined in the cstring header file is:
int strcmp( const char* lhs, const char* rhs );
- The
strcmp()compares the contents of lhs and rhs lexicographically. - The sign of the result is the sign of difference between the first pairs of characters that differ in lhs and rhs.
strcmp() Undefined Behavior
The behaviour of strcmp() is undefined if:
- either of lhs or rhs do not point to C-strings (null-terminated strings)
Example 1: C++ strcmp()
Output
Comparing Megadeth and Metallica: -1 Comparing Metallica and Megadeth: 1 Comparing Megadeth and Megadeth: 0
Example 2: Use strcmp() in a User-Defined Function
Output
Army follows Armstrong Armstrong precedes Army Armstrong and Armstrong are same Army and Army are same