• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strcmp and if statement

 
Omkar Shetkar
Ranch Hand
Posts: 81
1
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

To understand strcmp() function, I have written a test program.



Output:

strcmp(indira,ujwal): -12
strcmp(indira,chandan): 6
indira > ujwal
indira > chandan


Expected Output:

strcmp(indira,ujwal): -12
strcmp(indira,chandan): 6
indira < ujwal
indira > chandan


Why is the difference in output for comparison between strings "Indira" and "Ujwal"?
Please clarify.
 
Omkar Shetkar
Ranch Hand
Posts: 81
1
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got the answer!

In the ifstatement, when the conditional expression evaluates to a nonzero value, the
computer will jump to the statements controlled by the ifstatement and execute them
right away. If the expression evaluates to a value of zero, the computer will ignore those
statements controlled by the ifstatement.


Sorry for posting query too early.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15452
42
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed, you should have written something like this instead:

 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Omkar Shetkar wrote:

Expected Output:

strcmp(indira,ujwal): -12
strcmp(indira,chandan): 6
indira < ujwal
indira > chandan




Why are -12 and 6 the expected outputs? The man page says (vaguely) that the return values are 0, some value greater than zero, or some value less than zero. I somehow remember them as -1, 0 and 1, but I may be getting that from other languages.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest way to compare Strings for ASCIIbetical order is to subtract chars in corresponding positions from each other. Just as in Java®, a C char is a number, only in C it only occupies 8 bits.

U is the 21st letter and I the 9th, so 12 is 21 - 9.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic