Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does strcmp return if two similar strings are of different lengths?

Tags:

c

strcmp

I understand that if you have 'cat' (string1) and 'dog' (string2) in strcmp (this is a C question) then the return value of strcmp would be less than 0 (since 'cat' is lexically less than 'dog').

However, I am not sure what would happen with strcmp if this happened:

string1: 'dog'
string2: 'dog2'.

What would strcmp return? Less than zero, zero, or greater than? For context, I am trying to write a comparator function that compares strings and would like to account for strings starting with the same characters. One string may have an extension (such as '2' in 'dog2' in the example above).

EDIT: This is not a duplicate question. The question that this is allegedly similar to asks what the return type represents - I am saying what happens when the strings are identical up to a point but then one of them stops whilst the other continues.

like image 541
Daniel Soutar Avatar asked Apr 09 '16 15:04

Daniel Soutar


1 Answers

It returns the difference at the octet that differs. In your example '\0' < '2' so something negative is returned.

like image 93
hroptatyr Avatar answered Sep 28 '22 19:09

hroptatyr