What does this function do?

int mystery( const char *s1, const char *s2 ) { for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) { if( *s1 != *s2 ) { return 0; } //end if } //end for return 1; } 

I know that it prints errors, but that is exactly so. thanks guys, I need it to start too, and I already added a variable declaration, but im getting a compiler error that says

In the function `int main()':
error: a function-definition is not allowed here before '{' token
error: expected
`int main()':
error: a function-definition is not allowed here before '{' token
error: expected
`int main()':
error: a function-definition is not allowed here before '{' token
error: expected
, 'or `;' before the '{' token

+4
source share
5 answers

It compares two lines, returning 1 if line one starts with line two or vice versa and 0 if not.

+11
source

It returns 0 if the shorter one (s1, s2) does not coincide with the beginning of the longer one. Strings can be of different lengths, but one must be a substring, starting from the beginning of the other.

Change Osh Chart beat me up. Drive him away in front of me.

+4
source

Is it worth explaining?

  for( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ ) { 

The first element in a for loop, before the first ';' makes the initial setup, there is no need.
Thus, the for loop works as long as any of the characters pointed to by s1 and s2 are non-zero. Zero marks the end of a line in c and C ++.
The last part of the for loop is what needs to be done in each loop - in this case, it moves the pointers s1 and s2 to point to the next character on each line.

  if( *s1 != *s2 ) { return 0; 

If the characters pointed to by s1 and s2 do not match, i.e. we found the first different character in two lines, return 0, i.e. false

 return 1; 

If we get to the end of one of the lines, and we did not find any characters that would be different, return 1 - i.e. true.

Thus, the function returns true if the lines are identical or one line begins with another, and false - lines and different characters.

+3
source

This code will look like this in Java

 int specificComparison(String s1, String s2){ int minLength = Math.min(s1.length(), s2.length()); if(s1.substring(0, minLength).equals(s2.substring(0, minLength)){ return 1; }else{ return 0; } } 
+1
source

It looks like this function returns 1 when two strings are equal and 0 is not.

At least that could be the intention.

0
source

All Articles