Difference between strcmp and strncmp functions in C

Interview Questions

  • What is the difference between strcmp() and strncmp() string functions in C.

 

What is the difference between strcmp() and strncmp() string functions in C

The function int strcmp(const char *str1, const char *str2); compares string pointed by str1 with string pointed by str2. This function compares both string character by character. It will continue comparison until the characters mismatch or until a terminating null-character is reached.

The function int strncmp(const char *str1, const char *str2, size_t n); compares first n characters string pointed by str1 with first n characters of string pointed by str2. It will continue till n characters or until the characters mismatch or until a terminating null-character is reached before n characters.

The main difference between strcmp and strncmp function is that strncmp compares only first n characters whereas strcmp function compares characters till end of the string.