Potential applications of the icrement/decrement operators

AI Thread Summary
The discussion highlights the practical applications of increment (++) and decrement (--) operators in programming, particularly in languages like C, C++, Java, and C#. These operators can improve performance by reducing the number of operations required in loops, especially when dealing with large datasets. While both incrementing and adding one yield the same result, the increment operator can be more efficient in terms of execution time and code readability. Additionally, the operators allow for more concise expressions, making code easier to write and understand. Overall, their use is particularly beneficial for managing indexes or pointers in programming.
stonecoldgen
Messages
108
Reaction score
0
So I'm starting to learn how to program and I just learned how these operators work (difference between pre and post, etc.).

However, I have a question, what real application can these operators have in actual software development?

I mean, if for instance I have a variable with an X value and I want to print X+1, wouldn't it be the same to use the + operator? Or is it something that has to do with economizing memmory?

Thanks.
 
Technology news on Phys.org
stonecoldgen said:
So I'm starting to learn how to program and I just learned how these operators work (difference between pre and post, etc.).

However, I have a question, what real application can these operators have in actual software development?

I mean, if for instance I have a variable with an X value and I want to print X+1, wouldn't it be the same to use the + operator? Or is it something that has to do with economizing memmory?

Thanks.
The result would be the same, but the amount of time used to do the calculation would be slightly less for the increment operator, assuming that the compiler didn't optimize the addition operation into an increment operation. It would be difficult to tell the difference between the two operations if you just did it once, but if your program uses a for loop thousands or more times, you might be able to tell the difference (again assuming compiler optimization is turned off).

Increment and decrement operators (++ and --) were introduced in C back in the 70s and are present in other languages that are descended from C, such as C++, Java, and C#.

C was designed to be a mid-level language, somewhere between low-level assembly languages and high-level languages such as Fortran and COBOL. The intent by Brian Kernighan and Dennis Ritchie (the designers of C) was that C would be used to create operating systems.

In the interest of performance, Kernighan and Ritchie incorporated a number of operators in C that had direct counterparts in assembly languages. These include the increment and decrement operators. If a number to be changed is already in a register, it can incremented or decremented in one clock cycle. In comparison, adding 1 by ordinary addition to a number that's in a register requires a load instruction for loading another register with 1, and then calling an add instruction to perform the addition. The same is true for decrementing versus subtracting 1 from a value in a register. By reducing the number of operations needed to increment or decrement a number in a register, Kernighan and Ritchie were able to reduce the amount of time needed to perform operations that are used very often in programs.
 
I agree that the compiler will optimize += 1 down to ++ in most cases.

However ++ is a lot quicker to type e.g.

Code:
a[i] = 12  // eww
i += 1     // this is bad

a[i++] = 12 // i prefer this

If possible, ++i is generally better than i++ because the postfix version may in some cases need create an extra instance of the item, if you are not dealign with simple data types.

In C or C++, the order of operation of ++ on each side of an expression is not guaranteed by C++ standard therefore avoid stuff this

Code:
a++ * ++a; // undefined compiler behaviour

It has been too long since I did any C, but I think a = i++ or somethign might also be danger.
 
Last edited:
Forgetting about optimising the code (because at this low level, that is the compiler's job, not yours!) there is an important feature of the increment and decrement operators. That is that the are operators, so you can use them inside expressions. "i = i + 1;" is a statement, not an expression, so you can't "embed" it in a bigger expression.

Splitting up "a[i++] = b," into "a = b; i = i + 1;" is longwinded, and if you later realize the code should have said "a[j++] = b;" you have to remember to repalce i with j three times not once.

You can also use the operators in ways that would be messy to write without them. For example
Code:
while ( a[i++] > b[j++] )
{
   /* do something */
}
is easy read and see undesrstand what is going on (OK, it might nto be easy for a beginner, but programmers don't stay beginners for ever). But rewriting that without using "++" is not only longer, it's also hard to get it right. For example this code does NOT do the same thing, because i and j will have different values when the loop terminates.
Code:
while ( a[i] > b[j] )
{
    i = i + 1;
    j = j + 1;
   /* do something */
}
 
Mark44 said:
In the interest of performance, Kernighan and Ritchie incorporated a number of operators in C that had direct counterparts in assembly languages. These include the increment and decrement operators.
Also on some processors, such as the PDP 11, Motorola 68000 series, ... , stack operations are generalized to include pre and post incrementing / decrementing with pointer registers. Stack operations would use pre-decrement with a pointer for push, and post-increment with a pointer for pop. Note that operand size affects the amount of the increment or decrement, 1 for an 8 bit operand, 2 for a 16 bit operand, 4 for a 32 bit operand, 8 for a 64 bit operand, or some multiple of these values if moving data to / from a set of registers.

Mark44 said:
In comparison, adding 1 by ordinary addition to a number that's in a register requires a load instruction for loading another register with 1, and then calling an add instruction to perform the addition.
Many processors, such as the ones used in PCs (AMD, Intel) include an add or subtract immediate (to a register or a location in memory), so there's no need to load a register with the increment or decrement value, but it does take up code space in the instruction for the immediate value.
 
Last edited:
It is probably a good thing to also consider the nature of do-while and simply while statements in how they check for the termination condition to exit the loop.

The while statement does the check before the start of each iteration and the do-while loop checks it after each iteration. These kinds of things will help you put a lot of this pre-post stuff into context.
 
AlephZero said:
You can also use the operators in ways that would be messy to write without them. For example
Code:
while ( a[i++] > b[j++] )
{
   /* do something */
}
is easy read and see undesrstand what is going on (OK, it might nto be easy for a beginner, but programmers don't stay beginners for ever). But rewriting that without using "++" is not only longer, it's also hard to get it right. For example this code does NOT do the same thing, because i and j will have different values when the loop terminates.
Code:
while ( a[i] > b[j] )
{
    i = i + 1;
    j = j + 1;
   /* do something */
}

I don't want to start an argument, and I have no dispute about how each of those two code snippets operate. I do however find it an interesting example of how two different people can look at the same facts and come to opposite conclusions ;)

Personally I find the second code block more transparent and easier to get right. To me it's far more obvious that the seconds loop terminates with i,j pointing to the first elements in their respective arrays for which the comparison fails (compared with the first one where the loop terminates with i,j both one past this point).
 
Last edited:
My guess is the main reason that pre and post increment / decrement became part of the C language is that these operations were already included in machine language on some computers at the time the C language was being developed. It provided a simple way for programmers to take advantage of processors that included those operations. The C implementation of these operations just made them a bit more general purpose.

Getting back to the original question, these operations are probably more useful for indexes or pointers as opposed to general data variables.
 
AlephZero said:
it might nto be easy for a beginner, but programmers don't stay beginners for ever,

But not all them attain expert level :-)

Not wanting to start an argument but I regard readibility as more important than memory usage (in general, unless you're really pushed for resources).

The problem is that in a software development environment, (1) programmers work in teams and don't have mind reading skills, (2) after the work is done, the software will live on for 30 years, being maintained by a less-skilled maintenance programmer. (A "code monkey").

I understand sci-programming may be different from commercial development, but there are parallels: one day you will ask your PHD student to make some adjustment to your code, or you will pay a code-shop to add some boring non-domain specific functionality like automatically push the results to the web.

In the software engineering community, it is common practice amongst "reputable" shops that if you do anything unusual or which might confuse another guy lookng at your code, you should explain what you have done in a comment.

Edit: I am not saying write dumb code. I am saying, in many cases, readability is important.
 
  • #10
AlephZero said:
there is an important feature of the increment and decrement operators. That is that the are operators, so you can use them inside expressions. "i = i + 1;" is a statement, not an expression, so you can't "embed" it in a bigger expression.

Actualy this is wrong.

C/C++ = assigment is an operator (the = operator) and has value as an expession equal to the right hand side.

Code:
a = i = i + 1; // valid, defined in the C standard

EDIT: your example i = i + 1; is only a statement as you put a ; on the end. Take that ; off and it works fine as an expression.
 
Last edited:
  • #11
AlephZero said:
Forgetting about optimising the code (because at this low level, that is the compiler's job, not yours!) there is an important feature of the increment and decrement operators. That is that the are operators, so you can use them inside expressions. "i = i + 1;" is a statement, not an expression, so you can't "embed" it in a bigger expression.

rorix_bw said:
Actualy this is wrong.
I disagree, but I agree with your edit below.
rorix_bw said:
C/C++ = assigment is an operator (the = operator) and has value as an expession equal to the right hand side.

Code:
a = i = i + 1; // valid, defined in the C standard

EDIT: your example i = i + 1; is only a statement as you put a ; on the end. Take that ; off and it works fine as an expression.
Just to clarify:
Assignment expression: i = i + 1
Assignment statement: i = i + 1;

The only difference here is the semicolon at the end.

As rorix_bw already noted, the value of an assignment expression is the value that is stored in the variable on the left side of =. That's something that eludes beginning C/C++ programmers a lot, when they confuse assignment (=) with equality (==).

Code:
x = 5;

if (x = 2)
{ 
   printf("x is 2");
}
else
{
   printf("x is %d", x);
}
Many C beginners would predict that this code would print "x is 5", but that's not what happens, precisely because the value of an assignment expression (x = 2 in the if condition) evaluates to 2, which can be considered to be true.
 
  • #12
Yes the semantics of the natural language were unclear, but I thought the example was really bad and needed additional explanation, especially when = instead of == is such a common error.
 
Back
Top