简体   繁体   中英

What's the function of increments and decrements operators in any programming language?

I'm having a hard time understanding increments and decrements operators. In general, I see the "++ and --" post condition and preconditions in many variables inside or outside the loop. I know that it adds one or subtract one from the variable. But what's the purpose ? like for intance.

int house =1; 
/// block of code. Usually if statements, loops, other type of code you name       it. 
house++
For(int i =0; i<5;i++)  

I thinking its like a way to control a block of items. Let me know Thank you.

As you said, the increment operators increases a value by one, and the decrement operator decreases a value by one.

The postfix operator will return the variable's value and then change the variable.

int a = 5;
System.out.println(a++); // Outputs 5, before incrementing the variable.
System.out.println(a); // Outputs 6

The prefix operator will return the variable's new value after changing the variable.

int a = 5;
System.out.println(--a); // Outputs 4, after decrementing the variable.
System.out.println(a); // Outputs 4

This action of changing the variable before or after evaluation is the same for both the decrement and increment operators.

The way that this ordering of evaluation and mutation of the variable works is via the JVM's stack, and in which order values are pushed and variables are changed.

The purpose is exactly what you write: to increment or decrement an integer type (typically) variable.

It's common syntactic sugaring that provides a concise idiom that represents a commonplace task.

The idea of doing the same set of operations over and over again in a loop is very common in computer programming, and incrementing or decrementing counters, pointers or whatever is often useful in such a scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM