简体   繁体   中英

I don't understand ++ operators in c++

在此处输入图片说明

when I compile this, I get

j is: 28  k is: 50
V H 

What I do not understand is, why is the j++ and k++ 28 and 50 and not 27 and 48, respectively? I don't understand why it adds 3+, and not 1+.

The condition (txt[j] == txt[k]) is true for 3 values, '-', 'I', and '-'. So you add three to 25, and add 3 to 47. The before/after increment is only different on the line it happens.

If you had:

int x = 10;
int y = 10;
cout << x++;
cout << ++y;

you would see that x's value would be 10 at the time it was printed, and y's value would be 11.

if you then just printed them again without changing them a second time they should both be 11.

===========================

With your values it works like this:

Txt [25] is letter '-' in the string. It's like the 4th '-' in. Text[47] is also the letter '-', it's like the 8th '-' in the string. The condition of the loop says to continue running the increment opperators on these two indexes while they are the same value. So they are the same, both get incremented. Now we look at letters 26, and 48. These are both 'I', which is the same again. So we increment a third time, 27, and 49 Are both '-' again, so we increment again. Now 28 is at 'V' (the start of 'VAAR'), and 50 is at 'H' the start of 'HOST'. 'H' is not equal to 'V' so we stop looping here.

You're starting your compare at "-IV" and "-IH" . So there are three characters that match.

Preincrement ++k and postincrement j++ both increment the variables. The difference in how they behave as right hand side arguments, eg int z = ++k; vs int z = k++; . The former increments k and assigns its new value to z . The latter assigns the current value of k to z and then increments k ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM