Help understanding something

This has bugged me since the last time i read this chapter, I never understood or felt comfortable reading the following.

for (i = 0; i < n && str[i]; i++)

What does the str[i] mean? I'm reading it as

"For integer i is = to 0, as long as i is less than n and str[i] evaluates to true, add one to i"

Is this the correct way to read the test condition?

The full code is :

1
2
3
4
5
6
7
8
9
10
11
12
13
//this function returns a pointer to a new string consisting of the first n characters in the String
char * left (const char * str, int n)
{
    if (n<0)
        n = 0;
    char * p = new char[n+1];
    int i;
    for (i = 0; i < n && str[i]; i++)
        p[i] = str[i];
    while (i <= n)
        p[i++] = '\0';
    return p;
}

Last edited on
str is an array (or pointer. They're actually the same, but arrays are easier to understand/explain). This means that str is not a single character, but a series of characters. To access the (i+1)'th character of str, the notation str[i] is used (The first letter is on spot '0'!). We call 'i' (or whatever name is used for the integer) the "index".

An example:
1
2
3
4
5
char onechar = 'r';
char multichar[10] = 'chararray';
if (mutichar[3] == a) { // check if 4th character is equal to a's value 'r'
  cout << "The third character of multichar is an r!"; // This will print!
}

Since the 4th letter in 'chararray' (Remember: indeces count from 0!) is an 'r', the if will return true.
Last edited on
To clarify:

To access the n'th character of str, the notation str[n-1] is used since arrays start counting from 0.

1
2
3
str[0] str[1] str[2] str[3]

1        2      3      4


str[3] is the 4th character in the string.

when declaring the array

char str[10]

This means there are up to 10 characters in the array (technically 9 readable chars in C since the last position of a string would be a nullbyte) ranging from str[0] to str[9].
Last edited on
As to why the && str[i] is there - because C strings are terminated by the "zero" character '\0'. It has a value of 0, and as well all know 0 evaluates to false. Any other character is non-zero and therefore true. Basically it's a shorthand for && str[i]!='\0'
Last edited on
georgewashere wrote:
What does the str[i] mean? I'm reading it as

"For integer i is = to 0, as long as i is less than n and str[i] evaluates to true, add one to i"

Is this the correct way to read the test condition?


Yes. That is correct.

Any non-zero value for str[i] is TRUE and the value zero is FALSE.

This means that str[i] will return false at the end of a c-style string because they are zero terminated.
Last edited on
new topic made.
Last edited on
New question = new topic. Makes it easier to find stuff.
Topic archived. No new replies allowed.