understanding code example

Hi, I am learning about using loops to compare arrays. I need help understanding the following example in my book.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// compstr1.cpp -- comparing strings using arrays
#include <iostream>
#include <cstring>     // prototype for strcmp()
int main()
{
  using namespace std;
  char word[5] = "?ate";
  
  for (char ch = 'a'; strcmp(word, "mate"); ch++)
    {
      cout << word << endl;
      word[0] = ch;
    }
  cout << "After loop ends, word is " << word << endl;
  return 0;
}


How does the strcmp function work? Also, what does the for loop body do each time.
char word[5] = "?ate" is simply initializing the character array, right?
Last edited on
How does strcmp work? See http://www.cplusplus.com/reference/cstring/strcmp/

The key thing to notice is that the function returns either 0 or non-0. Non-0 converts to true and 0 to false.

On first call to strcmp the question is: Are "?ate" and "mate" equal? They are not and therefore the first character in the array is replaced by value of ch.

Run the program. See the output. It helps in this case.
How does the strcmp function work?

If you don't have a textbook or reference book to look this up in, then there are many good references online that are only a Google search away - including this very site:

http://www.cplusplus.com/reference/cstring/strcmp/

Also, what does the for loop body do each time.

Which line are you having trouble with?

Line 11 writes the current contents of word to standard output.
Line 12 sets the value of the first elements of word to be the same as ch.

If you run it, you'll see this happening.

char word[5] = "?ate" is simply initializing the character array, right?

Correct.
Last edited on
Thanks I understood the program now. Ran the program as well.
The link on strcmp helped. Thanks again.
You're welcome!
Topic archived. No new replies allowed.