Unary Operator in C
0 257
In C programming, unary operators operate on a single operand.
There are several unary operators in C, including:
1 Increment (++):
Increases the value of the operand by 1.
2 Decrement (--):
Decreases the value of the operand by 1.
3 Address-of (&):
Returns the memory address of the operand.
4 Pointer Indirection (*):
Returns the value at the address specified by its operand.
5 Unary Plus (+):
Returns the operand's value.
6 Unary Minus (-):
Returns the negative value of the operand.
7 Logical NOT (!):
Inverts the logical state of the operand.
8 Bitwise NOT (~):
Inverts each bit of the operand.
Examples:
Increment and Decrement Operators:
// Program for Increment and decrement operator #include<stdio.h>int main() { int c = 5, d = 10; printf("Initial values of c and d are : c = %d, d = %d\n", c, d); ++c; // Increment c --d; // Decrement d printf("After incrementing and decrementing d the value becomes: c = %d, d = %d\n", c, d); return 0; }
Output:
Initial values of c and d are : c = 5, d = 10 After incrementing and decrementing d the value becomes: c = 6, d = 9
Address-of and Pointer Indirection Operators:
// Program for Address of and pointer Indirection Operators #include<stdio.h>int main() { int num = 20; int *ptr = # // Pointer to num printf("Value of num: %d\n", num); printf("Address of num: %p\n", &num); printf("Value at address stored in ptr: %d\n", *ptr); return 0; }
Output:
Value of num: 20 Address of num: 0x7ffcaf9e61d4 Value at address stored in ptr: 20
Unary Plus and Minus Operators:
// Program for unary plus and minus operators #include<stdio.h>int main() { int num = 5; printf("Unary Plus (+num): %d\n", +num); printf("Unary Minus (-num): %d\n", -num); return 0; }
Output:
Unary Plus (+num): 5 Unary Minus (-num): -5
Logical NOT and Bitwise NOT Operators:
// Program for logical NOT and Bitwise NOT Operators #include<stdio.h>int main() { int a = 0, b = 5; printf("Logical NOT (!a): %d\n", !a); // 1 (true) printf("Logical NOT (!b): %d\n", !b); // 0 (false) printf("Bitwise NOT (~a): %d\n", ~a); // -1 printf("Bitwise NOT (~b): %d\n", ~b); // -6 return 0; }
Output:
Logical NOT (!a): 1 Logical NOT (!b): 0 Bitwise NOT (~a): -1 Bitwise NOT (~b): -6
These examples demonstrate the basic usage of unary operators in C.
Each operator has specific use cases and behaviors that make it essential for various programming tasks.
Share:
Comments
Waiting for your comments