Friday, July 29, 2016

C Basics - Miscellaneous Operators in C

There are a few other important operators supported by the C Language.

Operator Syntax Description Example
Size-of sizeof Returns the size of a variable. sizeof(x), where x is integer, will return 2 or 4.
Address-of &x Returns the address of a variable. &x; returns the actual address of the variable x.
Indirection *x Pointer to a variable. *x ; will be pointer to a variable x
Comma x,y Comma operator, sequencing int x, y;
Cast (type) Cast operator can be used to explicitly convert the value of an expression to a different data type. typeconversion x = (int)y;
Function call x(y,z) Function expression int main(int argc, char *argv[]);
Expression Grouping x*(y+z) Grouping expression or sub-expression x*(y+z)
Subscript x[y] Array expression int months[12];
Structure Deference x->y Structure element selection through pointer struct time *now; now-> hour = 10;
Structure reference x.y Structure element selection by reference struct time now; now. hour = 10;

#include <stdio.h>

int main() 
 int x = 21, z = 0; 
 int *y;
 printf("Sizeof x is  %d\n", sizeof(x));
 y = &x;
 printf("Address-of x is 0x%x\n", y);
 printf("Indirection. Pointer to x: %d\n", *y); 

   return 0;
The output of the above program would be
Sizeof x is  4
Address-of x is 0x28ff34
Indirection. Pointer to x: 21

comma operator:
A set of expression separated by comma is a valid constant in the C language. For example i and j are declared by the statements

int i , j;

In the above declaration, right hand side consists of two expressions separated by comma. The first expression is j=10 and second is j+20. These expressions are evaluated from left to right. ie first the value 10 is assigned to j and then expression j+20 is evaluated so the final value of i will be 30.

cast operator:
Cast operator can be used to explicitly convert the value of an expression to a different data type. Its general format is

(data type) expression

int i= (int)3.14; 
In the above statement, the value of i is 3.

float j= (float)10/2 
In the above statement, the value of j is 5.0

Related topics:
Overview of Operators in C   |   Arithmetic Operators in C   |   Relational Operators in C   |   Logical Operators in C   |   Bitwise Operators in C   |   Compound Assignment Operators in C   |   Conditional Operators in C   |   Operator Precedence and Associativity in C

List of topics: C Programming

No comments:

Post a Comment