user864752
user864752

Reputation: 1

Why string compare returns -1 even though both strings are same?

I am getting -1 instead of 0 in string comparison I have used following code

set s1 "sekhar" 
set s2 "sekhar"
puts [string compare s1 s2]

Upvotes: 0

Views: 167

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137807

When you do:

string compare s1 s2

You are comparing the string literals s1 and s2. Since s1 is lesser according to the rules (which are basically the same as for the C strcmp() function with enhancements) you get -1 as result.

To compare the strings with those names, you need to read the variables before feeding them into string compare. You do this by prefixing the names with $ (which in Tcl means “read this variable right now”):

string compare $s1 $s2

Internally, Tcl passes values around by reference and reduces variable accesses to indexes into a local variable table where it can (i.e., in procedures). This operation is actually pretty fast in practice.

Upvotes: 1

Related Questions