I had this question for a while - is it possbile (not intended, but if this "error" can occur) to actually increase AND decrease integer with ANY operation at the same time, so the result will be screwed integer? like this
1 2 3 4 5
int a = 0;
//some code
a++;
//meanwhile at the very same time, not the same code, so another thread or something
a -= 5
if it would go normally, the a would == -4, however is there any way that it will screw itself, and the "a" will be -5, or 1, or just will be somehow broken?
Multiple threads accessing the same memory at the same time results in a race condition. Race conditions result in undefined behavior. Literally anything can happen. a might remain unchanged... or it might have 4 subtracted... or it might be filled with random garbage... or your program might crash.
To prevent this, memory shared between threads needs to be guarded. Typically this is done either with a mutex (see the <mutex> header), or by making the variable atomic (see the <atomic> header).
Yes, C++ doesn't stop you from shooting yourself in the foot.
you can do it in the same expression: std::cout << (a -=5) << (a++);, but the behavior of the program that attempts to evaluate such expression is undefined
Likewise with threads - if one thread executes a++; and another a-=5;, without synchronization or without changing the type of a to std::atomic<int>, the behavior of the program is undefined.