2020-04-15

Does calculating a value in condition in C++ for loop in advance make the loop run much faster ?

my  goal is to get the right half of a string I enter

Example:
Input: abcd
Output:dc
Input:abcde
Output:ed

Here's Code One. It works fine

#include <iostream>
#include <string>

int main(void) {
        std::string str;
        std::cin >> str;

        std::string::size_type nstr = str.size();

        std::string str2;

        for (std::string::size_type i = nstr - 1; i != ((nstr % 2 == 0) ? (nstr / 2 - 1) : (nstr / 2)); --i)
                str2.push_back(str[i]);

        std::cout << str2 << std::endl;

        return 0;
}


Now I have modified the above code and get Code Two which also works fine.


#include <iostream>
#include <string>

int main(void) {
        std::string str;
        std::cin >> str;

        std::string::size_type nstr = str.size();

        std::string str2;

        std::string::size_type nstr2 = (nstr % 2 == 0) ? (nstr / 2 - 1) : (nstr / 2);

        for (std::string::size_type i = nstr - 1; i != nstr2; --i)
                str2.push_back(str[i]);

        std::cout << str2 << std::endl;

        return 0;
}


I guess the Code Two works faster than Code One because the nstr2 is calculated in advance before the loop.

Otherwise, (nstr % 2 == 0) ? (nstr / 2 - 1) : (nstr / 2lc needs to be calculated in each loop.

Question: Is my guess correct ?  And is it necessary in C++ pragramming?


https://stackoverflow.com/questions/3221577/what-is-a-loop-invariant

No comments:

How to Add a Directory to PATH in Linux

 https://linuxize.com/post/how-to-add-directory-to-path-in-linux/ When you type a command on the command line, you’re basically telling the ...