-10

I have slice of C code and I want to ask when I input some string for example "up". Jump to the code looks like : (strcmp(pdirection,"up")==0)
So, what does it mean, I don't understand especially ==0

the slice of code is at call by reference position.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
Shawn
  • 23
  • 5
  • When 2 strings are equal `strcmp` function will return `0` – Himanshu May 01 '15 at 11:14
  • Look up on `strcmp`. It returns 0 if the two strings which are passed have the same content. – Spikatrix May 01 '15 at 11:14
  • strcmp() returns the difference of the first two characters which are not the same in the two strings. If there is no difference the equation results in 0. – rfreytag May 01 '15 at 11:15
  • Just look at this [tutorial](http://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm) – Himanshu May 01 '15 at 11:15
  • 2
    `==` is the equality sign, it checks if the L.H.S. is equal to R.H.S. Also, `strcmp()` function return an integer which is the difference between the two strings: http://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm – Ayushi Jha May 01 '15 at 11:16

2 Answers2

3

From the manual

int strcmp(const char *s1, const char *s2);

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

So, if both the strings are equal, then strcmp() returns 0

The == is the equal to operator, which checks if the value on both sides are equal. Let's see what the C standard has to say

6.5.9

equality-expression == relational-expression

3 The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence.108) Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. For any pair of operands, exactly one of the relations is true.

Your code was probably

if( strcmp(pdirection,"up") == 0 )
    do_something;

So, if the string stored in pdirection is equal to "up", then the function strcmp() will return 0 and the == 0 part checks if the value is equal to 0, and if it is equal to 0, then do_something is done.

Arun A S
  • 6,421
  • 4
  • 29
  • 43
0

The strcmp(char *str1, char *str2) return the difference between the 2 strings. So if the 2 strings are equal, the difference is 0.

In fact, it scans the 2 strings one char at a time, until it reaches 2 different chars or passes the end of one string (the last char of a string in C is a char whose ASCII value is 0, noted '\0').

The function returns the first difference it meets between the 2 strings.

Nicolas Buquet
  • 3,880
  • 28
  • 28