Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Operators in C / C++

Operators are the foundation of any programming language. Thus the functionality of
C/C++ programming language is incomplete without the use of operators. We can
define operators as symbols that help us to perform specific mathematical and logical
computations on operands. In other words we can say that an operator operates the
operands. For example, consider the below statement:
c = a + b;
Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

Types of Operators in C / C++


1. Arithmetic Operators: These are the operators used to perform
arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–).
Arithmetic operator are of two types:
I. Unary Operators: Operators that operates or works with a single operand are
unary operators. For example: (++ , –)
II. Binary Operators: Operators that operates or works with two operands are binary
operators. For example: (+ , – , * , /)
 Addition: The ‘+’ operator adds two operands. For example, x+y.
 Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
 Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
 Division: The ‘/’ operator divides the first operand by the second. For
example, x/y.
 Modulus: The ‘%’ operator returns the remainder when first operand is
divided by the second. For example, x%y.
 Increment: The ‘++’ operator is used to increment the value of an integer.
When placed before the variable name (also called pre-increment operator),
its value is incremented instantly. For example, ++x.
And when it is placed after the variable name (also called post-increment
operator), its value is preserved temporarily until the execution of this
statement and it gets updated before the execution of the next statement. For
example, x++.
 Decrement: The ‘ – – ‘ operator is used to decrement the value of an integer.
When placed before the variable name (also called pre-decrement operator),
its value is decremented instantly. For example, – – x.
And when it is placed after the variable name (also called post-decrement
operator), its value is preserved temporarily until the execution of this
statement and it gets updated before the execution of the next statement. For
example, x – –.

1
Presented by: Irfan Haider
2. Relational Operators: Relational operators are used for comparison of the values of two
operands. For example: checking if one operand is equal to the other operand or not, an
operand is greater than the other operand or not etc. Some of the relational operators are (==,
>= , <= ).
 ‘==’ operator checks whether the two given operands are equal or not. If so, it
returns true. Otherwise it returns false. For example, 5==5 will return true.
 ‘!=’ operator checks whether the two given operands are equal or not. If not, it
returns true. Otherwise it returns false. It is the exact boolean complement of
the ‘==’ operator. For example, 5!=5 will return false.
 ‘>’ operator checks whether the first operand is greater than the second operand.
If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
 ‘<‘ operator checks whether the first operand is lesser than the second operand. If
so, it returns true. Otherwise it returns false. For example, 6<5 will return false.
 ‘>=’ operator checks whether the first operand is greater than or equal to the
second operand. If so, it returns true. Otherwise it returns false. For
example, 5>=5 will return true.
 ‘<=’ operator checks whether the first operand is lesser than or equal to the
second operand. If so, it returns true. Otherwise it returns false. For
example, 5<=5 will also return true.

3. Logical Operators: Logical Operators are used to combine two or more


conditions/constraints or to complement the evaluation of the original condition in consideration.
The result of the operation of a logical operator is a boolean value either true or false.
 Logical AND: The ‘&&’ operator returns true when both the conditions in
consideration are satisfied. Otherwise it returns false. For example, a && b returns
true when both a and b are true (i.e. non-zero).
 Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in
consideration is satisfied. Otherwise it returns false. For example, a || b returns
true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a
and b are true.
 Logical NOT: The ‘!’ operator returns true the condition in consideration is not
satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e.
when a=0.

2
Presented by: Irfan Haider
4. Bitwise Operators: The Bitwise operators is used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then calculation is performed on the
operands. The mathematical operations such as addition , subtraction , multiplication etc. can
be performed at bit-level for faster processing.
 & (bitwise AND) Takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
 | (bitwise OR) Takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
 ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
 << (left shift) Takes two numbers, left shifts the bits of the first operand, the
second operand decides the number of places to shift.
 >> (right shift) Takes two numbers, right shifts the bits of the first operand, the
second operand decides the number of places to shift.
 ~ (bitwise NOT) Takes one number and inverts all bits of it
Following is an example C program.
/* C Program to demonstrate use of bitwise operators */
#include<stdio.h>
int main()
{
unsigned char a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a&b); // The result is 00000001
printf("a|b = %d\n", a|b); // The result is 00001101
printf("a^b = %d\n", a^b); // The result is 00001100
printf("~a = %d\n", a = ~a); // The result is 11111010
printf("b<<1 = %d\n", b<<1); // The result is 00010010
printf("b>>1 = %d\n", b>>1); // The result is 00000100
return 0;
}
Output:
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4

Following are interesting facts about bitwise operators.


1) The left shift and right shift operators should not be used for negative
numbers If any of the operands is a negative number, it results in undefined behaviour.
For example results of both -1 << 1 and 1 << -1 is undefined. Also, if the number is
shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33
is undefined if integers are stored using 32 bits. See this for more details.

3
Presented by: Irfan Haider
2) The bitwise XOR operator is the most useful operator from technical interview
perspective. It is used in many problems. A simple example could be “Given a set of

numbers where all elements occur even number of times except one number, find the
odd occurring number” This problem can be efficiently solved by just doing XOR of all
numbers.

// Function to return the only odd occurring element


int findOdd(int arr[], int n) {
int res = 0, i;
for (i = 0; i < n; i++)
res ^= arr[i];
return res;
}

int main(void) {
int arr[] = {12, 12, 14, 90, 14, 14, 14};
int n = sizeof(arr)/sizeof(arr[0]);
printf ("The odd occurring element is %d ", findOdd(arr, n));
return 0;
}
// Output: The odd occurring element is 90

3) The bitwise operators should not be used in place of logical operators.


The result of logical operators (&&, || and !) is either 0 or 1, but bitwise operators return an
integer value. Also, the logical operators consider any non-zero operand as 1. For example,
consider the following program, the results of & and && are different for same operands.

int main()
{
int x = 2, y = 5;
(x & y)? printf("True ") : printf("False ");
(x && y)? printf("True ") : printf("False ");
return 0;
}
// Output: False True

4) The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.
As mentioned in point 1, it works only if numbers are positive.

int main()
{
int x = 19;
printf ("x << 1 = %d\n", x << 1);
printf ("x >> 1 = %d\n", x >> 1);
return 0;
}
// Output: 38 9

4
Presented by: Irfan Haider
5) The & operator can be used to quickly check if a number is odd or even
The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value would be
zero.

int main()
{
int x = 19;
(x & 1)? printf("Odd"): printf("Even");
return 0;
}
// Output: Odd

6) The ~ operator should be used carefully


The result of ~ operator on a small number can be a big number if the result is stored in an
unsigned variable. And the result may be a negative number if the result is stored in a signed
variable (assuming that the negative numbers are stored in 2’s complement form where the
leftmost bit is the sign bit)

// Note that the output of the following program is compiler dependent


int main()
{
unsigned int x = 1;
printf("Signed Result %d \n", ~x);
printf("Unsigned Result %ud \n", ~x);
return 0;
}
/* Output:
Signed Result -2
Unsigned Result 4294967294d */

Assignment Operators: Assignment operators are used to assign value to a variable.


The left side operand of the assignment operator is a variable and right side operand of
the assignment operator is a value. The value on the right side must be of the same
data-type of variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
 “=”: This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
For example:
 a = 10;

 b = 20;
 ch = 'y';
 “+=”:This operator is combination of ‘+’ and ‘=’ operators. This operator first adds
the current value of the variable on left to the value on right and then assigns the
result to the variable on the left.
Example:
 (a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

5
Presented by: Irfan Haider
 “-=”:This operator is combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on right from the current value of the variable on left and then
assigns the result to the variable on the left.
Example:
 (a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
 “*=”:This operator is combination of ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on right and then
assigns the result to the variable on the left.
Example:
 (a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
 “/=”:This operator is combination of ‘/’ and ‘=’ operators. This operator first divides
the current value of the variable on left by the value on right and then assigns the
result to the variable on the left.
Example:
 (a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.

Data Types in C
Each variable in C has an associated data type. Each data type requires different
amounts of memory and has some specific operations which can be performed over it.
Let us briefly describe them one by one:
Following are the examples of some very common data types used in C:
 char: The most basic data type in C. It stores a single character and requires a single byte
of memory in almost all compilers.
 int: As the name suggests, an int variable is used to store an integer.
 float: It is used to store decimal numbers (numbers with floating point value) with single
precision.
 double: It is used to store decimal numbers (numbers with floating point value) with
double precision.

Different data types also have different ranges upto which they can store numbers.
These ranges may vary from compiler to compiler. Below is list of ranges along with the
memory requirement and format specifiers on 32 bit gcc compiler.

6
Presented by: Irfan Haider
DATA TYPE MEMORY (BYTES) RANGE FORMAT SPECIFIER

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 %f

double 8 %lf

long double 12 %Lf

7
Presented by: Irfan Haider
#include <stdio.h>
int main()
{
int a = 1;
char b ='G';
double c = 3.14;
printf("Hello World!\n");

//printing the variables defined above along with their sizes


printf("Hello! I am a character. My value is %c and "
"my size is %lu byte.\n", b,sizeof(char));
//can use sizeof(b) above as well

printf("Hello! I am an integer. My value is %d and "


"my size is %lu bytes.\n", a,sizeof(int));
//can use sizeof(a) above as well

printf("Hello! I am a double floating point variable."


" My value is %lf and my size is %lu bytes.\n",c,sizeof(double));
//can use sizeof(c) above as well

printf("Bye! See you soon. :)\n");

return 0;
}
Output:
Hello World!
Hello! I am a character. My value is G and my size is 1 byte.
Hello! I am an integer. My value is 1 and my size is 4 bytes.
Hello! I am a double floating point variable. My value is 3.140000 and my
size i
s 8 bytes.
Bye! See you soon. :)

8
Presented by: Irfan Haider
Integer literal in C/C++ (Prefixes and Suffixes)
Integer literal is a type of literal for an integer whose value is directly represented in
source code. For example, in the assignment statement x = 1, the string 1 is an integer
literal indicating the value 1, while in the statement x = 0x10 the string 0x10 is an
integer literal indicating the value 16(in decimal), which is represented by 10 in
hexadecimal (indicated by the 0x prefix).
Further, in x = “1” the “1” is a string literal(not a character or an integer literal), because
it is in quotes. The value of the string is 1, which happens to be an integer string.
Integer literals are expressed in two types i.e.,
1. Prefixes which indicates the base. For example, 0x10 indicates the value 16 in
hexadecimal having prefix 0x.
2. Suffixes which indicates the type. For example, 12345678901234LL indicates the
value 12345678901234 as an long long integer having suffix LL.

 Prefixes: They are basically represent in four types.


1. Decimal-literal(base 10):- a non-zero decimal digit followed by zero or more
decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). For example, 56, 78.
2. Octal-literal(base 8):- a zero followed by zero or more octal digits(0, 1, 2, 3,
4, 5, 6, 7). For example, 045, 076, 06210.
3. Hex-literal(base 16):- 0x or 0X followed by one or more hexadecimal digits(0,
1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F). For example, 0x23A,
0Xb4C, 0xFEA.
4. Binary-literal(base 2):- 0b or 0B followed by one or more binary digits(0, 1).
For example, 0b101, 0B111.
 Suffixes: They are represented in many ways according to their data types.
1. int:- No suffix are required because integer constant are by default assigned
as int data type.
2. unsigned int: character u or U at the end of integer constant.
3. long int: character l or L at the end of integer constant.
4. unsigned long int: character ul or UL at the end of integer constant.
5. long long int: character ll or LL at the end of integer constant.
6. unsigned long long int: character ull or ULL at the end of integer constant.

// C++ program to demonstrate the use of


// integer literal
#include <iostream>
using namespace std;

int main()
{
// PREFIXES
cout << 213 << '\n' // decimal integer literal
<< 0213 << '\n' // Octal integer literal
<< 0x213A << '\n' // hexadecimal integer literal
<< 0b101 << '\n' // binary integer literal

// SUFFIXES

9
Presented by: Irfan Haider
// long long literal
<< 1234567890123456789LL << '\n'

// unsigned long long literal


<< 12345678901234567890ull << '\n'

// automatic conversion of unsigned long long even


// without long long prefix
<< 12345678901234567890u;

return 0;
}
Output:
213
139
8506
5
1234567890123456789
12345678901234567890
12345678901234567890
1221300

Best of Luck!

Presented by
Irfan Haider
BS (6th Semester)
Department of Physics, AIOU Islamabad

10
Presented by: Irfan Haider

You might also like