When comparing the contents of two character strings, using ==
or !=
operators on char pointer or char values will compare the pointers or addresses rather than the actual character values. This can lead to incorrect comparison results. To properly compare character contents, use the strcmp()
or strncmp()
string comparison functions instead. These functions return 0
if the strings are equal or nonzero if they differ, providing an accurate character content comparison.
1#include <stddef.h>
2#include <string.h>
3
4int stringEqualityNonCompliant()
5{
6 char *s = "Hello";
7 // Noncompliant: Checking strin pointer instead of value
8 if (s == "World") {
9
10 return -1;
11 }
12return 0;
13}
1#include <stddef.h>
2#include <string.h>
3
4char *s = "Hello";
5
6int stringEqualityCompliant()
7{
8 // Compliant: Checking actual value using strcmp
9 if (strcmp(s, "World") == 0) {
10 return -1;
11 }
12return 0;
13}