ALERT

Cisco CloudCenter: Get the Hybrid IT Advantage

Decrement Operator

Definition - What does Decrement Operator mean?

A decrement operator, in the context of C#, is a unary operator. It returns a value of same type, with predefined value equal to the operand value minus one. The decrement operator is denoted by the symbol '—'.

A decrement operator supports both prefix and postfix notations. In case of prefix notation (denoted by --x, where x is a variable), the value of a variable is used in the expression after decrementing its original value. While using postfix notation (x--), the value of a variable before the decrement operation will be considered in the expression. A decrement operator can be used to change the pointer location by subtracting a value equal to the size (or pointer-type) from the address contained in the pointer variable.

Techopedia explains Decrement Operator

A decrement operator is usually used in loop iteration statements or in any context where there is a need to decrement by one unit. Features of decrement operator include:

  • The value returned by the decrement operator is stored in a location pointing to the variable.
  • The value returned by the operator becomes the result of the decrement operation.
  • Types which have predefined decrement operator implementation are numeric types, such as integer, sbyte, short, int, long, char, float, double, decimal, and enumeration type.
  • User-defined types can overload the decrement operator to implement necessary semantics.
  • While applying a decrement operator to the pointer, result depends on implementation. Exceptions are not thrown if the operation overflows the pointer domain.
  • The precedence of decrement operator allows postfix notation to have a higher precedence than the prefix form.

Note that, while using a decrement operator, the operand must be an expression representing a variable, property access, or indexes. Additionally, If the decrement operator is used with prefix notation for operand, the property or indexer must have a get and set accessor to avoid compilation errors. Furthermore, if a decrement operator is used for a pointer, the pointer can be of any type except void*.

A decrement operator should be used to set a variable and not to a value. Usage of a decrement operator more than once in a single expression can cause unpredictable results mostly because of optimization applied by the compiler. Hence, it is suggested to use a decrement operator after understanding the order of evaluation, while using both postfix and prefix notation along with its precedence in the set of C# operators. Postfix and prefix notations of a decrement operator cannot have separate operator implementation.

This definition was written in the context of C#
Share this: