Why do these two programs give different results in VC ++ 2008?

Why do these two programs give different results in VC ++ 2008?

In the end, the same strings are compared.

strcmp__usage.c

#include <stdio.h> #include <string.h> main() { char targetString[] = "klmnop"; printf ("Compare = %d\n", strcmp(targetString, "abcdef")); printf ("Compare = %d\n", strcmp(targetString, "abcdefgh")); printf ("Compare = %d\n", strcmp(targetString, "jlmnop")); printf ("Compare = %d\n", strcmp(targetString, "klmnop")); printf ("Compare = %d\n", strcmp(targetString, "klmnoq")); printf ("Compare = %d\n", strcmp(targetString, "uvwxyz")); printf ("Compare = %d\n", strcmp(targetString, "xyz")); } 

Output

 Compare = 1 Compare = 1 Compare = 1 Compare = 0 Compare = -1 Compare = -1 Compare = -1 

strncmp_usage.c

 #include <stdio.h> #include <string.h> main() { char targetString[] = "klmnopqrstuvwxyz"; int n = 6; printf ("Compare = %d\n", strncmp(targetString, "abcdef", n)); printf ("Compare = %d\n", strncmp(targetString, "abcdefgh", n)); printf ("Compare = %d\n", strncmp(targetString, "jlmnop", n)); printf ("Compare = %d\n", strncmp(targetString, "klmnop", n)); printf ("Compare = %d\n", strncmp(targetString, "klmnoq", n)); printf ("Compare = %d\n", strncmp(targetString, "uvwxyz", n)); printf ("Compare = %d\n", strncmp(targetString, "xyz", n)); } 

Output

 Compare = 10 Compare = 10 Compare = 1 Compare = 0 Compare = -1 Compare = -10 Compare = -13 
+4
source share
2 answers

Both strcmp and strncmp provide a guarantee that the result will include:

A zero value indicates that both lines are equal. A value greater than zero indicates that the first character that does not match has a larger value in str1 than in str2; And a value less than zero indicates the opposite.

The real number returned (1 / -1 or 12 / -13) is implementation specific and can be any value. The only part that matters is that both return 0, less than zero, or greater than zero. In this regard, they give the same answer.

+3
source

From strncmp:

Returns an integer value indicating the relationship between the lines: A zero value indicates that the characters being compared on both lines are equal. A value greater than zero indicates that the first character that does not match has a larger value in str1 than in str2; And a value less than zero indicates the opposite.

Clearly, strcmp always returns 1 or -1 for unimportant characters, and strncmp returns the difference between non-null characters. Since this behavior is undefined, this is not a problem.

+2
source

Source: https://habr.com/ru/post/1385281/


All Articles