slashmais
slashmais

Reputation: 7155

Why do these increments give different results?

The operator ++ should be equivalent to + 1, so why does the following example produce different results?

#include <iostream>
#include <string>

int main()
{
    int i, n=25;
    std::string s1="a", s2="a", s1p="", s2p="";

    for (i=0;i<=n;i++)
    {
        s1p += s1;
        s1 = s1.at(0) + 1;

        s2p += s2;
        s2 = s2.at(0)++;
    }
    std::cout << "s1p = " << s1p << "\n" << "s2p = " << s2p << "\n";

    return 0;
}

Ouput:
s1p = abcdefghijklmnopqrstuvwxyz
s2p = aaaaaaaaaaaaaaaaaaaaaaaaaa

Upvotes: 0

Views: 207

Answers (3)

Takiro
Takiro

Reputation: 470

++ and +1 are not equivalent. To substitute n++; you have to use n = n+1; (or n+=1 if you want). ++ actually increments a variable whereas +1 just returns the result of the arithmetic operation. also note that n++ and ++n have different behavior.

n = 1;
i = 1;

a = ++n;
b = i++;
c = i;

The output for a, b and c would be

a: 2
b: 1
c: 2 

Upvotes: 2

James Kanze
James Kanze

Reputation: 153899

The statement:

s2 = s2.at(0) ++;

is curious, to say the least. You're modifying s2 twice in the same statement. On a build-in type, this would be undefined behavior; on a user defined type (like std::string), it's just confusing. And because the side effects of the ++ must occur before the call to operator=, the ++ is effectively a no-op; any modification of any character in s2 is overwritten by the assignment.

If your goal is to assign a totally new value to the string, based on its first character (and ignoring any additional characters it might contain), then your modification of s1 is the correct solution. If your goal is to modify the first character in the string, leaving any other characters unchanged, then the correct solution is simply s.at(0) ++, ++ s.at(0) or s.at(0) += 1, without any assignment. (The second is the most idiomatic, when the results are not otherwise used.) And of course, if you want to build up a string of successive characters of the alphabet:

std::string s;
for ( char ch = 'a'; ch <= 'z'; ++ ch ) {
    s += ch;
}

would be the most idiomatic (even though it's formally wrong, and won't work in some environments: there's no guarantee that the letters of the alphabet occupy consecutive codepoints in the encoding).

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258548

The post-increment returns the value previously held by the variable.

Think of x++ (post-increment) as

int y = x;
x = x+1;
return y;

and of ++x (pre-increment) as

x = x+1;
return x;

To achieve your desired result, you need pre-increment.

Upvotes: 9

Related Questions