Section 6n

Special Case - Comparing C-Style Strings


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

A Slightly Different Kind of Test

Comparing Non-Primitive Data

As you learned previously, the primitive data in C (e.g., the char, the int, the double, and as it is treated in this reference the bool) can all be tested with normal Boolean operators. However, as has also been discussed previously, string or text data which is not found in the C programming language must also be tested. Thus the C_Style string, or c-string) is created from C language tools to handle that situation. However, because it is its own data quantity, there are no Boolean operators or tests for C-Style strings.

So, since we essentially invented the data quantity, we had to invent a way to compare it. And we did. As you recall, you have used the strcpy, strcat, and strlen functions to handle string operations. You will now be introduced to the strcmp function.

The strcmp function accepts two parameters which can be called stringOne and stringTwo, and returns an integer value as follows:

Large Caveat. Some library functions will return a negative one (-1) or positive one (+1) as the "less than" and "greater than" results, respectively. Never count on this. The specification for the function is "less than zero" and "greater than zero" and if you test your results against specific values, your testing process may fail.

Ugly Bug. Unfortunately and rather insidiously, your code might work when you compile it in your system but then fail when compiled in a different system so you will not know you have introduced a bug into code you (and the other folks) thought was working.

Here is a brief example of the use of strcmp:

// Set names
char firstName[] = "Sally";
char secondName[] = "Bill";

// Check for first name alphabetically greater than second name
if( strcmp( firstName, secondName > 0 ) )
{
printf( "%s is greater than %s\n", firstName, secondName );
}

You can view a few other examples in this video. It is worth your time to try this out on your own so take advantage.

Moving Ahead

Now that you have had an opportunity to learn how to test all of the kinds of data you are working with, you can move along to even more interesting part of computer programming. It just keeps getting better!