if alpha and beta were int variables, the statement alpha = --beta is equivelent to what statement?
also what would alpha = beta++ be equivilent to what statement. i know you add 1 to the first one but it doesn't seem right. any help would be appreciated.

Dani AI

Generated

Good clarifications from and — they correctly pointed out how prefix and postfix forms behave. A few practical follow-ups that often catch people new to C/C++:

Avoid mixing updates to the same object inside a single expression. Expressions that modify a variable more than once, or both read and modify it without a well-defined sequencing, can produce undefined behavior in C and C++. What looks deterministic on one compiler may break or change on another; see the cppreference discussion on evaluation order and sequencing for the language rules and examples: Order of evaluation.

When writing code with iterators or your own classes, prefer the prefix form when you do not need the old value. For user-defined types the postfix form typically creates a temporary copy (the signature is the dummy int parameter), so ++it is usually slightly cheaper than it++. The cppreference page on increment/decrement operators summarizes the typical signatures and recommended practice: Increment and decrement operators.

Keep expressions simple for readability and correctness. If behaviour is subtle or sequencing matters, split the work into separate statements or use temporary variables. For example, when iterating prefer the canonical loop form with prefix increment:

for (auto it = container.begin(); it != container.end(); ++it) {
    // use *it
}

These points complement the answers above while reducing surprises from performance quirks or undefined behavior.

Recommended Answers

All 4 Replies

When you say --x, x is decremented by one before being used in the expression. Likewise, ++x increments x by one before using it in the expression. x++ or x-- will perform the increment or decrement after using the value in the expression.

int x = 0;
int y;

y = x++; // y is set to 0
y = ++x; // y is set to 2

The -- and ++ operators are initially confusing. They are unique to C and C++.

What --a means is "make a = a - 1 before you do anything else." Same with ++a : a is modified first.

The a-- means "make a = a -1 after you do everything else." Likewise with a++ .

C and C++ like shorthand statements. So alpha = beta++ is the same as the two statements: alpha = beta; beta = beta + 1; Hope this helps.

[EDIT] Alas, too slow...

>They are unique to C and C++.
Not really. While ++ and -- were invented for B (and inherited by C), quite a few languages now use them.

thank you for your help. i greatly appreciate it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.