Unary operators play a crucial role in C programming, allowing operations on a single operand. Let's explore the various unary operators, their priorities, and how they function in expressions.
Introduction to Unary Operators:
Unary operators, such as Increment (++), Decrement (--), Minus (-), Address (&), and SizeOf, act on a single operand. They hold the highest priority in expression evaluation and follow right-to-left associativity.
Operator | Description (or) Action |
---|---|
++ | Increment Operator |
-- | Decrement Operator |
- | Minus Operator |
& | Address Operator |
SizeOf | Sizeof Operator |
Increment (++) and Decrement (--) Operators :
The Increment operator (++), when used as a suffix or prefix to a variable, adds one to its operand. Similarly, the Decrement operator (--), subtracting one from its operand. Understanding their usage is crucial:
x = x + 1; // x++ - Post increment x = x - 1; // x-- - Post decrement
If used as a suffix, post increment/decrement operations occur. If used as a prefix, pre increment/decrement operations take place.
Examples
Example 1
x = 20; y = 10; z = x * y++; // Result: z = 20 * 10 = 200; (y is incremented after the operation)
Example 2
x = 20; y = 10; z = x * ++y; // Result: z = 20 * 11 = 220; (y is incremented before the operation)
Minus (-) Operator
The Minus operator changes the algebraic sign of a value. It is a unary operator that takes only one operand.
Example
int x = -50; int y = -x; // y is assigned the value of 50 through x
Address (&) and Size SizeOf Operators
The Sizeof operator provides the bytes occupied by a variable, varying from variable to variable. The Address (&) operator prints the memory address of a variable.
Program : Example
#include<stdio.h> main() { int x = 2; float y = 2; printf("sizeof(x)=%d bytes \n", sizeof(x)); printf("sizeof(y)=%d bytes \n", sizeof(y)); printf("address of x=%u and y = %u", &x, &y); }
Output :
sizeof (x) = 2 bytes sizeof (y) = 4 bytes Address of x = 4066 and y = 25096
Understanding unary operators is essential for precise and efficient C programming. They allow developers to manipulate variables, control flow, and optimize memory usage effectively. Explore these operators to enhance your programming skills.
0 Comments