File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes C / C++ and the fly likes strcmp and if statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Languages » C / C++
Bookmark "strcmp and if statement" Watch "strcmp and if statement" New topic
Author

strcmp and if statement

Omkar Shetkar
Ranch Hand

Joined: Jun 22, 2006
Posts: 51

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.

http://mynotesontech.wordpress.com/
Omkar Shetkar
Ranch Hand

Joined: Jun 22, 2006
Posts: 51

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

Joined: Aug 16, 2005
Posts: 14426
    
  23

Indeed, you should have written something like this instead:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Red Smith
Ranch Hand

Joined: Aug 05, 2007
Posts: 136
    
    1
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

Joined: Oct 13, 2005
Posts: 40029
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: strcmp and if statement