I thought I understood how i++ and ++i, increment operators worked but after playing with a code example I am now very confused.
Minimum Viable Code Example
#include <iostream>
int main()
{
std::cout << "i k \n";
int i{1}, k{0};
k = i++ + ++i;
std::cout << i << " " << k << "\n";
i = 1;
k = i + ++i;
std::cout << i << " " << k << "\n";
i = 1;
k = 2 + ++i;
std::cout << i << " " << k << "\n\n";
i = 1;
k = i++ + i;
std::cout << i << " " << k << "\n";
i = 1;
k = i++ + 1;
std::cout << i << " " << k << "\n";
}
Output
i k
3 4
2 4
2 4
2 3
2 2
When is the increment operator applied? After the value is used once? How far after a value is used can another ++i increment operators change the value when it was used?
Hopefully, these are not stupid questions ahaha
Aucun commentaire:
Enregistrer un commentaire