Operators in C (Unary, Binary, Ternary Operators)

This article is the continuation of the Series on the C programming tutorial and carries the discussion on C language programming and its implementation. In our last tutorial, we discussed the Introduction to C programming. In this article, we are going to see operators in C programming. It aims to provide easy and practical examples for understanding the C program.

Whenever we write code in the C programming language, mostly we use two basic concepts. Those are,

In this article, we are going to learn about C Programming operators. So let’s begin.

Operators in C Programming Language

What are Operands?

Before we learn Operators, we will have to know what are operands.

Operands are values or variables used in computer programming to perform operations. They can be numbers, strings, or other data types. For example, in “5 + 32” the “5” and “32” are the operands. Instead of these numbers, we can also use variables.

What are Operators in C?

Operators in C are symbols that perform specific operations on operands. They are used to manipulate data and perform calculations in a C program. In simple, Whenever you perform an operation in data, you need to use some symbols that are known as operators.

Example:

sum = a + b
Operand in C Programming Language

There are many types of Operators in C.

What are the Precedence and Associativity of Operators

The precedence of operators refers to the order in which different operators are evaluated in an expression. It determines the sequence in which operations are performed. Operators with higher precedence are evaluated before those with lower precedence.

The exact precedence rules may vary depending on the programming language being used. It is important to understand the precedence of operators to ensure that expressions are evaluated correctly.

The associativity of operators refers to the order in which operators of the same precedence are evaluated. In programming languages, operators can be either left-associative or right-associative. Left-associative operators are evaluated from left to right, while right-associative operators are evaluated from right to left.

The associativity of an operator determines how expressions containing multiple operators are evaluated. Understanding the associativity of operators is important for writing correct and efficient code.

Use of Operator Precedence and Associativity

Precedence and Associativity are the two things that are used in operators in a condition to evaluate the order of the condition when they do not have brackets.

Example:

In mathematics, we follow the BODMAS rule. Similarly, In C programming, we follow the operator precedence and associativity rule.

int x = 4 + 3 * 2;

The result of the above condition is 10 instead of 14. Since the * operator has higher precedence than the + operator. Hence, the + operator is evaluated after the * operator.

PrecedenceOperatorMeaningAssociativity
1()ParenthesesLeft to right
1[] Array element referenceLeft to right
1-> Member access via pointerLeft to right
1. Member access via object nameLeft to right
1++ Postfix incrementLeft to right
1--Postfix decrementLeft to right
1!Logical NOT operatorLeft to right
1~Bitwise complement operatorLeft to right
1+ Unary plus operatorLeft to right
2Unary minus operatorRight to left
2++ Prefix IncrementRight to left
2--Prefix DecrementRight to left
2 *Indirection operatorRight to left
2sizeof()Size of operatorRight to left
2(type)TypecastRight to left
3.*Dereference operatorLeft to right
3->*Dereference operatorLeft to right
4* Multiply Left to right
4/ DivideLeft to right
4% ModulusLeft to right
5+ Binary additionLeft to right
5Binary subtractionLeft to right
6<< Bitwise left shift Left to right
6>>Bitwise right shiftLeft to right
7< Less thanLeft to right
7<=Less than or equal toLeft to right
7>Greater thanLeft to right
7>=Greater than or equal toLeft to right
8== Equal toLeft to right
8!=Not equal toLeft to right
9&Bitwise ANDLeft to right
10^Bitwise XORLeft to right
11|Bitwise ORLeft to right
12&&Logical ANDLeft to right
13||Logical ORLeft to right
14?:Conditional operator Right to left
15=Simple assignmentRight to left
15*= Assign productRight to left
15~=Assign bitwise complementRight to left
15/=Assign quotientRight to left
15%=Assign remainderRight to left
15+=Assign sumRight to left
15-=Assign differenceRight to left
15&=Assign bitwise ANDRight to left
15^=Assign bitwise XORRight to left
15|=Assign bitwise ORRight to left
15<<=Assign bitwise left shiftRight to left
15>>=Assign bitwise right shiftRight to left
16,Comma OperatorLeft to Right
Operator Precedence and Associativity Table

Note: post ++ and -- operators have higher precedence than pre ++ and -- operators

Types of Operators in C

C programming language has divided the categories into three types of operators and from that, it has been classified into seven types of sub-operators, which we will learn in this article.

Let’s see the details using the below diagram.

Types of C Programming Operators

Unary Operator

It is an operator that requires a single operand to operate/work. Three types are available in the unary operator.

Increment and decrement operators cannot be used in constant numbers. It is only used with variables. So let’s see the details one by one.

Increment Operator (++)

The increment operator is used to increment or add the value by 1. There are two types.

  • pre-increment and
  • post-increment

Pre-increment Operator (++x)

When we use the increment operator before an operand, it is called pre-increment. (It means first the increment will happen, and then the value is assigned to it). For example ++x -> 1 + x.

Syntax:

int main()
{
    x = ++x;                 //pre-increment
    //statements
}

Example:

#include <stdio.h>
int main()
{
    int x=5,y;
    y = ++x;
    printf("x = %d\ny = %d",y,x);
    return 0;
}

Output:

x = 6
y = 6

Note:- In this program inside a main() I have assigned a value of 5 to the variable ‘x‘ which is an original value, then the value of 5 is incremented first by ++x which is 1 + 5 = 6, and now the value of 6 is assigned to the ‘x‘ variable and the result stored in ‘y‘ variable is 6 only after pre-increment.

Post-increment Operator (x++)

When we use the increment operator after an operand, it is called post-increment. (It means first the value will be assigned to it and then the increment will happen). For example x++ -> x + 1.

Syntax:

int main()
{
    x = x++;                 //post-increment
    //statements
}

Example:

#include <stdio.h>
int main()
{
    int x=5,y;
    y = x++;
    printf("x = %d\ny = %d",y,x);
    
    return 0;
}

Output:

x = 5
y = 6

Note: In this program inside a main() I have assigned a value of 5 to the variable ‘x‘ which is an original value, then the value of 5 is assigned first, and after it is incremented by x++ which is 5 + 1 = 6 and now the value of 5 is assigned to the ‘x‘ variable and the result stored in ‘y‘ variable is 6 only after post-increment.

Decrement Operator (- -)

The decrement operator is used to decrement or subtract the value by 1. There are two types.

  • pre-decrement
  • post-decrement

Pre-decrement Operator (--x)

When we use the decrement operator before an operand, it is called pre-decrement. (It means first the decrement will happen, and then the value is assigned to it). For example --x -> 1 - x.

Syntax:

int main()
{
    x = --x;                 //pre-decrement
    //statements
}

Example:

#include <stdio.h>
int main()
{
    int x=5,y;
    y = --x;
    printf("x = %d\ny = %d",y,x);
    
    return 0;
}

Output:

x = 4
y = 4

Note:- In this program inside a main() I have assigned a value of 5 to the variable of ‘x’ which is an original value then, the value of 5 is decremented first by --x which is 1 - 5 = 4 and now the value of 4 is assigned to the ‘x’ variable and the result stored in the ‘y’ variable is 4 only after pre-decrement.

Post-decrement Operator (x--)

When we use the decrement operator after an operand, it is called pre-decrement. (It means first the value will be assigned, and then the decrement will happen). For example x-- -> x - 1.

Syntax:

int main()
{
    x = x--;                 //pre-decrement
    //statements
}

Example:

#include <stdio.h>
int main()
{
    int x=5,y;
    y = x--;
    printf("x = %d\ny = %d",y,x);
    
    return 0;
}

Output:

x = 5
y = 4

Note: In this program inside a main() I have assigned a value of 5 to the variable of ‘x’ which is an original value then the value of 5 is assigned first, and after it is incremented by x– – which is 5 - 1 = 4 and now the value of 5 is assigned to the ‘x’ variable and the result in the ‘y’ variable is 4 only after post-increment.

Sizeof() Operators

sizeof() the operator is a unary operator which can be used for the size of its operand. sizeof() the operator is used differently. It is used in datatype and conditions. In sizeof() datatype, it is used int, char, float, double, etc. and it returns the memory size of the datatype. The format specifier of sizeof() is %zu which is mentioned in the below program.

Syntax:

sizeof(condition);

Here, a condition can be a data type or a variable of any type. It returns the sizeof() the given condition.

#include <stdio.h>
int main()
{
    printf("sizeof char = %zu\n",sizeof(char));
    printf("sizeof int = %zu\n",sizeof(int));
    printf("sizeof float = %zu\n",sizeof(float));
    printf("sizeof double = %zu",sizeof(double));
}

Output:

sizeof char = 1
sizeof int = 4
sizeof float = 4
sizeof double = 8

Note: sizeof() operator is a system-dependent operator that can run in a 32-bit or 64-bit system compiler.

#include <stdio.h>
int main()
{
    int i=20;
    char c='C';
    double d=20.52;
    float f=3.4;
    
    printf("Maximum bytes = %d",sizeof(i + c + d + f));
}

Output:

Maximum bytes = 8

In the sizeof() operator which case of size will be the maximum, the compiler will execute that datatype first as it is mentioned in the above program. Here of double datatype is more than the other datatypes so the compiler executes first.

Binary Operator

It is an operator in which the minimum requirement of two operands, for example is (10 + 5). Here, ’10’ and ‘5’ are operands, and ‘+’ is an operator. The binary operator is divided into five categories.

Syntax:

(operand 1) operator (operand 2)

Types of Binary Operators

Arithmetic Operator(+,-,*,/,%)

Arithmetic operators are the special operators in C language. It is used for mathematical operations only with a minimum of two operands.

Example:

#include <stdio.h>
int main()
{
    int a = 4,  b = 2, c;
    
    c = a + b;
    printf("a + b = %d \n",c);
    c = a - b;
    printf("a - b = %d \n",c);
    c = a * b;
    printf("a * b = %d \n",c);
    c = a / b;
    printf("a / b = %d \n",c);
    c = a % b;
    printf("a % b = %d",c);
    
    return 0;
}

Output:

a + b = 6 
a - b = 2 
a * b = 8 
a / b = 2 
a % b = 0

Assignment Operator (=,+=,-=,*=,/=,%=)

Assignment operators are also special operators in the C programming language. It is used to assign the value to a variable. The left side operand is a variable and the right side operand of the assignment operator is a value.

The value on the right side must be of the same data type as the variable on the left side, otherwise, the compiler will throw an error.

Example:

#include <stdio.h>
int main()
{
    int a = 5, b;
    
    b = a;      // b is 5
    printf("b = %d\n", b);
    b += a;     // b is 10 
    printf("b = %d\n", b);
    b -= a;     // b is 5
    printf("b = %d\n", b);
    b *= a;     // b is 25
    printf("b = %d\n", b);
    b /= a;     // b is 5
    printf("b = %d\n", b);
    b %= a;     // b = 0
    printf("b = %d\n", b);
    return 0;
}

Output:

b = 5
b = 10
b = 5
b = 25
b = 5
b = 0

Logical Operator/Expressions (&&,||,!)

Logical operators are used to combine two or more conditions, It returns either 0 ---> false or 1 ---> true depending upon whether the expression is true or false. It is commonly used in decision-making in C programming.

Let us consider, suppose if you have a value of a = 50, b = 10, c; then you will get, c = a > b which is true. So, 1 will be stored in the c. And if b = 100 then it will be as false and c will be having 0. So the concept in this logical operator says that it depends on a > b whether it is true or false.

Similarly, in such cases, there will be a situation like you having more than one condition and at that time you can use either &&,|| expressions.

Types of logical operator/expression

ABA&&B
TRUEFALSEFALSE
FALSETRUEFALSE
FALSEFALSEFALSE
TRUETRUETRUE
Table of Logical AND Operator (&&)

The Logical AND operator will return true only if all the conditions are true.

ABA||B
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE
TRUETRUETRUE
Table of Logical AND Operator (||)

The Logical OR operator will return true only if any one of the conditions is true.

AB
TRUEFALSE
FALSETRUE
Table of Logical NOT Operator (!)

The logical NOT operator will return true only if the condition is false.

Example of Logical AND (&&) Operator
#include <stdio.h>
int main()
{
    int x = 20, y = 10, z = 15;
    if(x < y && y < z)
    
    {
        printf(" X is a greater number");
    }
    else
    {
        printf(" X is not greater number");
        
    }
    
    return 0;
}

Output:

X is not greater number
Example of Logical OR (||) Operator
#include <stdio.h>
int main()
{
    int a = 20, b = 10, c = 15;
    if(c > a || c > b)
    
    {
        printf("C is neither a smaller nor greater number");
    }
    else
    {
        printf(" C is a greater number");        
    }
    
    return 0;
}

Output:

C is neither a smaller nor greater number
Example of Logical OR (!) Operator
#include <stdio.h>
int main()
{
    int i = 20, j = 10;
    if(i != j )
    
    {
        printf("i is not equal to j");
    }
    else
    {
        printf("i is equal to j"); 
    }
    
    return 0;
}

Output:

i is not equal to j

Short Circuit Operators/Expressions (&&, ||)

A short circuit is the way of evaluation used by the compiler to optimize the code because of how much fast the program will execute in less time than that much better will be its proficiency, So to reduce the time complexity in a program we use to evaluate this short circuit operator or expression in this article, It is also known as logical short circuit operators or expressions in C programming language.

Short circuit evaluation for logical AND (&&)

If the first condition is false then the compiler will not execute the next condition, it will be a short circuit in the first condition only.

Example of short circuit evaluation for logical AND (&&)
#include <stdio.h>
int main()
{
    int a = 10, b = 5, c;
    
    c = ((++a > 15) && (++b > 2));
    printf("A = %d\nB = %d\nC = %d",a,b,c);
    
    return 0;
}

Output:

A = 11
B = 5
C = 0

Note: Here I have taken two variables of a = 10, b = 2 and, I have pre-increment the two conditions with logical short circuit && operator c = (++a>15 && ++b>2), So now if the first condition is getting false according to the logical short circuit AND operator, then the compiler will not move to check the next condition rather the second condition might be true or false. It will simply short-circuit after the first condition.

Short circuit evaluation for logical AND (||)

If the first condition is true then the compiler will not execute the next condition, it will be a short circuit in the first condition only.

Example of short circuit evaluation for logical OR (||)
#include <stdio.h>
int main()
{
    int a = 10, b = 5, c;
    
    c = (++a > 5 || ++b > 10);
    printf("A = %d\nB = %d\nC = %d",a,b,c);
    
    return 0;
}

Output:

A = 11
B = 6
C = 1

Note: Similarly here I have also taken the same two variables of a = 10, and b = 2 and, I have pre-increment the two conditions with logical short circuit ||operator c = (++a>5 || ++b>10), So now if the first condition is getting true according to the logical short circuit OR operator then the compiler will not go to check the next condition.

But if there are several conditions and from that, if the first condition is getting false then the compiler will move to check the other condition until it gets the one condition as true, if the compiler gets a true condition it will simply get a short circuit, and it will not check rest condition whether it might be true or false.

Relational Operator (<,>,<=,>=,==,!=)

A relational operator is used to compare the values of arithmetic, logical, and character expressions of two operands. If the condition is true, it returns 1; if the relation is false, it returns 0.

Example:

#include <stdio.h>
int main()
{
    int a = 5, b = 3;

    printf("%d == %d\t = %d\n", a, b, a == b);
    printf("%d > %d\t = %d\n", a, b, a > b);
    printf("%d < %d\t = %d\n", a, b, a < b);
    printf("%d != %d\t = %d\n", a, b, a != b);
    printf("%d >= %d\t = %d\n", a, b, a >= b);
    printf("%d <= %d\t = %d\n", a, b, a <= b);
    
    return 0;
}

Output:

5 == 3	 = 0
5 > 3	 = 1
5 < 3	 = 0
5 != 3	 = 1
5 >= 3	 = 1
5 <= 3	 = 0

Bitwise Operator (&,|,^,~,<<,>>)

We have discussed these Bitwise operators in the next article.

Ternary Operator

The ternary operator is also called the conditional operator it works with three operands Expression1 Expression2 Expression3 either true value or false value, and it is denoted as ?:.

Conditional Operator

Whenever a program executes conditionally according to a particular statement, then we use conditional operators. Let us consider an example. Suppose Expression1 is the condition to be evaluated. If the condition(Expression1) is true then it will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then it will execute and return the result of Expression3.

Example:

Condition ? True : False

max = num1 > num2 ? num1 : num2;

#include <stdio.h>
int main()
{
    int num1,num2;
    printf("Enter two numbers:- ");
    scanf("%d %d",&num1,&num2);
    
    printf("The largest number is %d",(num1 > numm2 ? num1 : num2));
    return 0;
}
Enter two numbers:- 8 9
The largest number is 9

We also have the below special operators available in C programming.

You can read those also.

Frequently Asked Question

What are Operators in C?

Whenever you perform an operation in data, you need to use some symbols that are known as operators. The symbol operates in one or more operands or performs a specific logical operation on a variable or value in C languages, For example: (+, -, *, /, %). The data which we used to operate is called the operand.

What are the Precedence and Associativity of Operators in C?

The precedence of operators in C language indicates the order in which the operators will be involved in the condition. On the other hand, associativity defines the order in which operators of the same precedence will be evaluated in the same condition. Also, associativity can occur either from right to left or left to right.

What Use of Operator Precedence and Associativity?

Precedence and Associativity are the two things that are used in operators in a condition to evaluate the order of the condition when they do not have brackets.

What are the types of Operators?

  • Urnary operator
  • Binary operator
  • Ternary operator

When can we use the pre-increment operator instead of the post-increment operator in C?

In C, the pre-increment operator (++i) is used when we want to increase the value of a variable before using it in an expression. On the other hand, the post-increment operator (i++) is used when we want to increase the value of a variable after using it in an expression.

What are short circuit operators in C?

Short circuit operators in C are used to evaluate the second operand only if the result of the first operand is not sufficient to determine the final result of the expression. This means that if the first operand determines the outcome of the expression, the second operand is not evaluated, resulting in improved efficiency. There are two short circuit operators in C: the logical AND operator (`&&`) and the logical OR operator (`||`).

What is the conditional operator in C?

The conditional operator in C is a ternary operator that allows conditional evaluation of expressions. It takes three operands: a condition, a result when the condition is true, and a result when the condition is false. If the condition is true, the first expression is evaluated; otherwise, the second expression is evaluated. It is commonly used as a shorthand way to write simple if-else statements in C.

Condition ? expression1: expression2

In our next article, we will discuss the bitwise operators.

You can also read the below tutorials.

Linux Device Driver TutorialsC Programming Tutorials
FreeRTOS TutorialsNuttX RTOS Tutorials
RTX RTOS TutorialsInterrupts Basics
I2C Protocol – Part 1 (Basics)I2C Protocol – Part 2 (Advanced Topics)
STM32 TutorialsLPC2148 (ARM7) Tutorials
PIC16F877A Tutorials8051 Tutorials
Unit Testing in C TutorialsESP32-IDF Tutorials
Raspberry Pi TutorialsEmbedded Interview Topics
Reset Sequence in ARM Cortex-M4BLE Basics
VIC and NVIC in ARMSPI – Serial Peripheral Interface Protocol
STM32F7 Bootloader TutorialsRaspberry PI Pico Tutorials
STM32F103 Bootloader TutorialsRT-Thread RTOS Tutorials
Zephyr RTOS Tutorials – STM32Zephyr RTOS Tutorials – ESP32
AUTOSAR TutorialsUDS Protocol Tutorials
Product ReviewsSTM32 MikroC Bootloader Tutorial
VHDL Tutorials
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Table of Contents