Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Explain different types of expressions in C program
An expression in C is a combination of operators and operands that evaluates to a single value. An operand is a data item on which an operation is performed, and an operator indicates the operation to be performed.
Syntax
operand operator operand operator operand operand ? operand : operand
Types of Expressions
-
Primary expressions − Basic operands like variables, constants, or parenthesized expressions. Example:
a + (5*b) -
Unary expressions − Contains one operator and one operand. Examples:
++a,--b,!flag -
Binary expressions − Contains two operands and one operator. Examples:
a+b,c-d,x*y -
Ternary expressions − Contains three operands with conditional operator
?:. Format:condition ? value1 : value2 -
Postfix expressions − Operator appears after the operand. Examples:
a++,b-- -
Prefix expressions − Operator appears before the operand. Examples:
++a,--b
Example: Different Types of Expressions
The following program demonstrates various types of expressions in C −
#include <stdio.h>
int main() {
int a = 5, b = 3, c = 8, d = 2;
int result1, result2, result3, result4, result5, result6;
/* Primary expression */
result1 = a + (5 * b);
/* Unary expressions */
result2 = ++a; /* Prefix increment */
result3 = b--; /* Postfix decrement */
/* Binary expressions */
result4 = c + d;
result5 = c - d;
/* Ternary expression */
result6 = (a > b) ? a : b;
printf("Initial values: a=5, b=3, c=8, d=2
");
printf("Primary expression (a + (5*b)): %d
", result1);
printf("Unary prefix (++a): %d
", result2);
printf("Unary postfix (b--): %d
", result3);
printf("Binary addition (c+d): %d
", result4);
printf("Binary subtraction (c-d): %d
", result5);
printf("Ternary conditional (a>b ? a : b): %d
", result6);
return 0;
}
Initial values: a=5, b=3, c=8, d=2 Primary expression (a + (5*b)): 20 Unary prefix (++a): 6 Unary postfix (b--): 3 Binary addition (c+d): 10 Binary subtraction (c-d): 6 Ternary conditional (a>b ? a : b): 6
Key Points
- Expressions are evaluated based on operator precedence and associativity rules.
- Unary operators have higher precedence than binary operators.
- Ternary operator is right-associative and has lower precedence than most operators.
- Parentheses can be used to override default precedence.
Conclusion
Understanding expression types in C helps in writing efficient code and avoiding operator precedence errors. Each expression type serves specific purposes in program logic and data manipulation.
Advertisements
