Operators In C https://www.skillvertex.com/blog Fri, 10 May 2024 06:54:01 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://www.skillvertex.com/blog/wp-content/uploads/2024/01/favicon.png Operators In C https://www.skillvertex.com/blog 32 32 Operators In C https://www.skillvertex.com/blog/operators-in-c/ https://www.skillvertex.com/blog/operators-in-c/#respond Fri, 10 May 2024 06:54:01 +0000 https://www.skillvertex.com/blog/?p=1918 Read more]]>

Table of Contents

Operators In C

In C programming, operators are like tools that help you do things with data. They let you add, subtract, compare, and do other actions in your programs. Knowing how to use these operators is crucial for writing good C code. In this guide, we’ll take a closer look at C operators, what they do, and how to use them effectively in your programs.

What is an Operator In C

Operators are like symbols in programming that let us do different types of math, comparisons, and other operations on data. They basically work on the stuff we want to do things with, which we call operands. For instance, the ‘+’ sign is an operator used for adding numbers, like this:

c = a + b;

So, operators are like the tools we use to do math and more in programming.

the ‘+’ sign is called the addition operator, and ‘a’ and ‘b’ are the things we want to add, which we call operands. When we use the addition operator, it tells the computer to add ‘a’ and ‘b’ together.

Operators like ‘+’ are really important in C programming. They’re like the tools we need to do all sorts of calculations and operations in our programs. Without operators, C programming wouldn’t be as powerful and useful as it is.

Types Of Operators In C

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Other Operators

1. Arithmetic Operations in C

Arithmetic operators in C are the tools we use to do math operations with operands. Some common arithmetic operators include ‘+’, ‘-‘, ‘*’, ‘/’, ‘%’, ‘++’, and ‘–‘. These operators come in handy for various mathematical tasks.

Arithmetic operators can be categorized into two types:

a) Unary Operators

Unary operators in C are the ones that work with a single operand. These operators perform operations on a single value or variable. A couple of examples of unary operators are the increment operator ‘++’ and the decrement operator ‘–‘. They are used to increase or decrease the value of a variable by one. Unary operators are handy for making changes to a single value without the need for additional operands.

int val = 5;
cout<<++val;  // 6

b) Binary Operators:

Binary operators in C are the ones that work with two operands. These operators require two values or variables to perform operations. Some common binary operators include addition ‘+’, subtraction ‘-‘, multiplication ‘*’, and division ‘/’.

Binary operators are essential for performing various arithmetic and logical operations by combining two values or variables, making them fundamental components of C programming.

int a = 7;
int b = 2;
cout<<a+b; // 9

2. Relational Operators in C

Relational operators in C are used to compare the values of two operands. They allow you to determine whether one operand is equal to, greater than, less than, or not equal to the other operand. Examples of relational operators include ‘==’ (equal to), ‘>=’ (greater than or equal to), and ‘<=’ (less than or equal to).

These operators are extremely useful for making comparisons and decisions in your programs, such as checking if a number is equal to or greater than a certain value. Relational operators help you control the flow of your program based on conditions and comparisons between variables.

int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b

3. Logical Operator in C

Logical operators in C are powerful tools for combining and evaluating conditions or constraints in your program. These operators allow you to create complex conditions by joining multiple smaller conditions together. The result of a logical operation is always a Boolean value, which is either ‘true’ or ‘false’.

For instance, the logical AND operator, represented as ‘&&’ in C, returns ‘true’ only when both of the conditions being evaluated are satisfied or ‘true’. If either of the conditions is ‘false’, the result is ‘false’. So, ‘a && b’ returns ‘true’ only when both ‘a’ and ‘b’ are ‘true’ (i.e., non-zero). Logical operators are crucial for making decisions based on multiple conditions in your code.

cout<<((4 != 5) && (4 < 5));     // true

4. Bitwise Operators in C 

Bitwise operators in C are designed to perform operations at the individual bit level of operands. These operators allow you to manipulate data by operating on the binary representation of values. They are particularly useful for low-level programming and optimizing specific tasks.

For example, the bitwise AND operator, represented as ‘&’ in C, takes two numbers as operands and performs the AND operation on each pair of corresponding bits. The result is 1 (True) only when both bits being compared are 1. Bitwise operators are often used for tasks like setting or clearing specific bits within variables and for optimizing certain mathematical operations like addition, subtraction, and multiplication at the bit level to achieve faster processing in some cases.

int a = 5, b = 9;   // a = 5(00000101), b = 9(00001001)
cout << (a ^ b);   //  00001100
cout <<(~a);       // 11111010

5. Assignment Operators in C

Assignment operators in C are essential for assigning values to variables. They work by taking a variable on the left side and a value on the right side, and they store the value on the right into the variable on the left. It’s important to note that the data type of the value on the right must match the data type of the variable on the left, or else the compiler will generate an error.

In simpler terms, assignment operators are like the “equals” sign (=) in math, where you assign a value to a variable, and that value gets stored in the variable for later use in your program.

Different types of assignment operators are shown below: 

a) “=”

The simplest assignment operator in C is the ‘=’ operator. It’s used to assign the value on the right side to the variable on the left side. In other words, it sets the variable’s value to whatever is on the right. It’s like saying “variable = value.”

Example

a = 10;
b = 20;
ch = 'y';

b) “+=”

The simplest assignment operator in C is the ‘=’ operator. It’s used to assign the value on the right side to the variable on the left side. In other words, it sets the variable’s value to whatever is on the right. It’s like saying “variable = value.”

Example

(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

c) “-=” 

The operator you’re describing is the subtraction assignment operator, ‘-=’. It’s a combination of the ‘-‘ operator (subtraction) and the ‘=’ operator (assignment).

It takes the current value of the variable on the left, subtracts the value on the right from it, and then assigns the result back to the variable on the left. So, it’s like saying “variable = variable – value.” It’s a convenient way to update the value of a variable by subtracting another value from it.

Example

(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2

d) “*=” 

The operator you’re describing is the multiplication assignment operator, ‘=’. It combines the ‘‘ operator (multiplication) with the ‘=’ operator (assignment).

It takes the current value of the variable on the left, multiplies it by the value on the right, and then assigns the result back to the variable on the left. So, it’s like saying “variable = variable * value.” This operator is useful for updating a variable by multiplying its current value with another value.

Example

(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30

e) “/=”

The operator you’re describing is the division assignment operator, ‘/=’. It combines the ‘/’ operator (division) with the ‘=’ operator (assignment).

It takes the current value of the variable on the left, divides it by the value on the right, and then assigns the result back to the variable on the left. So, it’s like saying “variable = variable/value.” This operator is handy for updating a variable by dividing its current value by another value.

Example

(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.

6. Other Operators 

There are some other operators available in C used to perform some specific tasks

i. Size of operator

The sizeof operator is a crucial tool in C programming. It’s a compile-time unary operator that calculates the size of its operand. The result sizeof is an unsigned integral type, typically represented as size_t.

In essence, sizeof is used to determine the size, in bytes, of a variable or data type. This information is essential for memory allocation, especially when working with arrays or structures, and it helps ensure that your program allocates enough memory to store the data correctly.

ii. Comma Operator

The comma operator, represented by the token, is a binary operator in C. It works in a unique way: it first evaluates its left operand and discards the result, and then it evaluates the right operand and returns its value (and type).

One important thing to note is that the comma operator has the lowest precedence of all C operators. This means that other operations within an expression are evaluated before the comma operator.

Additionally, the comma serves a dual purpose as both an operator and a separator. It separates items in a list (like function arguments or variable declarations), and when used as an operator, it sequences the evaluation of expressions, often used for side effects or in loop constructs.

iii. Conditional Operator

The conditional operator in C takes the form: Expression1 ? Expression2 : Expression3. Here’s how it works:

  • Expression1 is the condition that gets evaluated.
  • If Expression1 is true, then the operator returns the result of Expression2.
  • If Expression1 is false, then the operator returns the result of Expression3.

In essence, the conditional operator is a concise way to perform a conditional check and return one of two possible values based on the outcome of the condition. It’s often used to replace simple if...else statements when you need to make a decision in a single line of code.

iv. dot (.) and arrow (->) Operators

Member operators are fundamental in C and C++ for referencing individual members (variables or functions) of classes, structures, and unions.

  1. Dot Operator (.): The dot operator is applied directly to the actual object. It is used when you have an instance of a class, structure, or union, and you want to access its members. For example, if you have an object myObject of class MyClass, you would access its members using myObject.member.
  2. Arrow Operator (->): The arrow operator is used when you have a pointer to an object. It is often used in situations where you dynamically allocate objects with new (in C++) or malloc (in C) and then access their members through a pointer. For example, if you have a pointer ptr to an object, you would access its members using ptr->member.

These operators are crucial for working with object-oriented programming concepts, data structures, and dynamic memory allocation, making it possible to access and manipulate the attributes and behaviors of objects.

v.  Cast Operator

Casting operators in C are used to convert one data type into another. They allow you to change the data type of a value or expression explicitly. For instance, if you have the value 2.2000 of type float and you want it to be an integer, you can use a cast like this: (int) 2.2000, which would result in 2.

A cast is a special operator that specifically instructs the compiler to perform the conversion. The most common syntax for casting is (type) expression, where type is the target data type, and expression is the value or expression you want to convert.

Casting is a powerful tool for controlling data types and ensuring compatibility in expressions or assignments, but it should be used with caution to avoid unexpected behavior or data loss.

vi.  &,* Operator

In C, the pointer operator & is used to obtain the address of a variable. For instance, &a will give you the actual memory address where the variable a is stored in memory.

On the other hand, the pointer operator * is used to declare and work with pointers. When used in a declaration like this, it indicates that ptr is a pointer to an integer variable. When used in expressions like this, it accesses the value that the pointer is pointing to. So, *ptr would give you the value of the integer variable that ptr is pointing to.

These operators are fundamental for working with pointers and memory addresses in C, allowing you to manipulate and work with data indirectly through pointers.

C Operators With Example

// C Program to Demonstrate the working concept of
// Operators
#include <stdio.h>
 
int main()
{
 
    int a = 10, b = 5;
    // Arithmetic operators
    printf("Following are the Arithmetic operators in C\n");
    printf("The value of a + b is %d\n", a + b);
    printf("The value of a - b is %d\n", a - b);
 
    printf("The value of a * b is %d\n", a * b);
    printf("The value of a / b is %d\n", a / b);
    printf("The value of a % b is %d\n", a % b);
    // First print (a) and then increment it
    // by 1
    printf("The value of a++ is %d\n", a++);
 
    // First print (a+1) and then decrease it
    // by 1
    printf("The value of a-- is %d\n", a--);
 
    // Increment (a) by (a+1) and then print
    printf("The value of ++a is %d\n", ++a);
 
    // Decrement (a+1) by (a) and then print
    printf("The value of --a is %d\n", --a);
 
    // Assignment Operators --> used to assign values to
    // variables int a =3, b=9; char d='d';
 
    // Comparison operators
    // Output of all these comparison operators will be (1)
    // if it is true and (0) if it is false
    printf(
        "\nFollowing are the comparison operators in C\n");
    printf("The value of a == b is %d\n", (a == b));
    printf("The value of a != b is %d\n", (a != b));
    printf("The value of a >= b is %d\n", (a >= b));
    printf("The value of a <= b is %d\n", (a <= b));
    printf("The value of a > b is %d\n", (a > b));
    printf("The value of a < b is %d\n", (a < b));
 
    // Logical operators
    printf("\nFollowing are the logical operators in C\n");
    printf("The value of this logical and operator ((a==b) "
           "&& (a<b)) is:%d\n",
           ((a == b) && (a < b)));
    printf("The value of this logical or operator ((a==b) "
           "|| (a<b)) is:%d\n",
           ((a == b) || (a < b)));
    printf("The value of this logical not operator "
           "(!(a==b)) is:%d\n",
           (!(a == b)));
 
    return 0;
}

Output

Following are the Arithmetic operators in C
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a++ is 10
The value of a-- is 11
The value of ++a is 11
The value of --a is 10

Following are the comparison operators in C
The value of a == b is 0
The value of a != b is 1
The value of a >= b is 1
The value of a <= b is 0
The value of a > b is 1
The value of a < b is 0

Following are the logical operators in C
The value of this logical and operator ((a==b) && (a<b)) is:0
The value of this logical or operator ((a==b) || (a<b)) is:0
The value of this logical not operator (!(a==b)) is:1

Time and Space Complexity

Time Complexity: O(1)
Auxiliary Space: O(1)

Precedence of Operators in C

PrecedenceOperatorDescriptionAssociativity
1()Parentheses (function call)left-to-right
[]Brackets (array subscript)left-to-right
.Member selection via object nameleft-to-right
->Member selection via a pointerleft-to-right
a++/a–Postfix increment/decrement (a is a variable)left-to-right
2++a/–aPrefix increment/decrement (a is a variable)right-to-left
+/-Unary plus/minusright-to-left
!~Logical negation/bitwise complementright-to-left
(type)Cast (convert value to temporary value of type)right-to-left
*Dereferenceright-to-left
&Address (of operand)right-to-left
sizeofDetermine size in bytes on this implementationright-to-left
3*,/,%Multiplication/division/modulusleft-to-right
4+/-Addition/subtractionleft-to-right
5<< , >>Bitwise shift left, Bitwise shift rightleft-to-right
6< , <=Relational less than/less than or equal toleft-to-right
> , >=Relational greater than/greater than or equal toleft-to-right
7== , !=Relational is equal to/is not equal toleft-to-right
8&Bitwise ANDleft-to-right
9^Bitwise exclusive ORleft-to-right
10|Bitwise inclusive ORleft-to-right
11&&Logical ANDleft-to-right
12||Logical ORleft-to-right
13?:Ternary conditionalright-to-left
14=Assignmentright-to-left
+= , -=Addition/subtraction assignmentright-to-left
*= , /=Multiplication/division assignmentright-to-left
%= , &=Modulus/bitwise AND assignmentright-to-left
^= , |=Bitwise exclusive/inclusive OR assignmentright-to-left
<>=Bitwise shift left/right assignmentright-to-left
15,expression separatorleft-to-right

FAQ- Operators In C

Q1. What are operators in C?

Ans. C operators are indeed essential features of the language, providing symbols and keywords to perform various types of operations, including mathematical, relational, bitwise, conditional, and logical manipulations. These operators are fundamental building blocks of C programming, enabling you to carry out a wide range of tasks within your programs. Whether you need to perform simple arithmetic calculations, make decisions based on conditions, or manipulate individual bits of data, C’s rich set of built-in operators offers the flexibility and power required to meet the needs of your programs.

Q2. What is an algorithm in C?

Ans. An algorithm is a precise set of step-by-step instructions used in computer programming to solve problems or perform tasks. It forms the foundation of writing software, allowing programmers to break down complex problems and provide clear directions to a computer on how to achieve a specific goal.

Q3. What is the relational operator in C?

Ans. Relational operators in C are designed for comparing two values. They examine the relationship between these values and provide a result based on that comparison. When the relationship is true, they return the value 1, and when it’s false, they return 0. These operators are crucial for making decisions and controlling the flow of a program based on comparisons between variables or values.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/operators-in-c/feed/ 0