Need help with FOR loop

I am encountering a difference in the serial number of the result. Could not figure it out why it is going like that.
Please explain if you figure out the logic behind the scene.

Code 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>

using namespace std;

int main ()
{
    char *bookstr[] = {"Math", "Physics", "Chemistry", "DSP"};

    for (int loop = 0; loop <= 3; )
        cout << loop << "." << bookstr[loop++] << "\n";

    return 0;
}


1.Math
2.Physics
3.Chemistry
4.DSP

Code 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main ()
{
    char *bookstr[] = {"Math", "Physics", "Chemistry", "DSP"};

    for (int loop = 0; loop <= 3; loop++)
        cout << loop << "." << bookstr[loop] << "\n";

    return 0;
}


0.Math
1.Physics
2.Chemistry
3.DSP
Last edited on
What do you mean by "the serial number of the result"?

EDIT: I think I see what you are asking. You are wondering why the first version prints 1,2,3,4 (maybe) while the second prints 0,1,2,3. It's because of "undefined behavior". It is (generally) an error to use a variable in the same expression where you are modifying it as you can't be sure whether you will get the old value or the new value. So the first version is wrong.
Last edited on
@dutch

Thank you. You got my question rightly.
Now, how can I get the following result through second version?
i.e.


1.Math
2.Physics
3.Chemistry
4.DSP


I tried this to obtain the above result, but I don't think it is a good approach.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main ()
{
    char *bookstr[] = {"a", "Math", "Physics", "Chemistry", "DSP"};

    for (int loop = 1; loop <= 4; loop++)
        cout << loop << "." << bookstr[loop] << "\n";

    return 0;
}
Last edited on
cout << loop+1 << etc;
you could also reindex so its from 1, so you can loop 1 to 4 instead of 0-3.

like this:
char *bookstr[] = {"unused","Math", "Physics", "Chemistry", "DSP"};
Last edited on
@jonnin

Thanks for the advise dear.
Something like this is probably best.

1
2
3
4
5
6
7
8
9
#include <iostream>

int main ()
{
    const char *bookstr[] = {"Math", "Physics", "Chemistry", "DSP"};
 
    for (int i = 0; i < 4; i++)
        std::cout << loop + 1 << "." << bookstr[loop] << "\n";
}

We usually start the loop index at 0 (when reasonable) and limit the loop by a less-than comparison against the size of the array (as opposed to less than or equal to one less than the size of the array).

Also, your char pointers are pointing to string literals, which are constant (you can't modify their chars). Hence the const.
Last edited on
@dutch

Thanks dear..
Topic archived. No new replies allowed.