DEV Community

3BiEiD
3BiEiD

Posted on • Edited on

A debate about x++; ⁉️🤔

Hi there, I hope you all are fine
let us talk a little bit about C++ programming language and take a deep dive into assignment operator (=) and post-increment operator (++)

#include <iostream>
using namespace std;
int main()
{
    int x = 5;
    x = x++;
    cout<<x;    // 5
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

The question is why x equals 5?
First of all, let us divide this statement into 3 parts
1) x
2) =
3) x++;
As the assignment operator = assigns the right side to the left side and returns the left side we should start with the right-most part which is x++;

x++ This is a post-increment operator which means it will evaluate the current value (5), and increment the value in memory for the upcoming operations (6).

When you use x++, the value of x is first used in the expression where x++ appears, and then x is incremented by 1.

until now everything is clear?
again
so x++; will do two things,

  • it'll give you a temporary value (we can say) which is 5, and,
    change x's real value in memory by 1.

  • but, if we say x = 900; we obviously say in this statement:
    change x's real value in memory and assign 900 to it.

If you notice same bold phrase repeated which means the same behavior in 2 different situations normal assignment and post-increment.

so finally the x = part will overwrite (x = 6 in memory) so it will remain 5.
I hope you got it 👍

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Collapse
 
abdomohamed785 profile image
3BiEiD • Edited

You can use pythontutor for more visualization of memory, Actually, it's a very great tool.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post