Skip to main content

Posts

Showing posts from January, 2014

Operator precedence and associativity in C language

Below is the table for operator precedence and associativity in C programming language. [ ] ( ) . -> ++ -- Array subscript Function Call Structure reference Structure dereference Postfix increment/Postfix decrement Left to right ++ -- + - ! ~ (type) *  & sizeof Prefix increment/Prefix decrement Unary plus/Unary minus Logical negation/One's complement Typecast operator Pointer dereference/Address of Size of type/variable in bytes Right to left *  /  % Multiplication/Division/Modulo Left to Right + - Addition/Subtraction Left to Right <<   >> Bitwise left shift/ Bitwise right shift Left to Right <    > <= >= Comparison less than/Comparision greater than Comparison less than or equal to Comparison greater than or equal to Left to Right ==   != Comparison equal to/Comparison not equal to Left to Right & Bitwise AND Left to Right ^ Bitwise XOR Left to Right | Bitwise OR Left to Right && ...

#ifdef, #ifndef and #endif directives in C

#ifdef If the named macro is defined, then the code between #ifdef and #endif will be compiled. #ifndef If the named macro is not defined, then the code between #ifndef and #endif will be compiled. #ifdef, #ifndef and #endif example in C #include <stdio.h> #define NAME "Raj" int main() { #ifdef NAME printf("#ifdef: Value of NAME is %s\n", NAME); #endif #ifndef VAL printf("#ifndef: macro VAL is not defined\n"); #endif return 0; }   Output:   jp@jp-VirtualBox:~/$ ./a.out   #ifdef: Value of NAME is Raj   #ifndef: macro VAL is not defined In the above program, macro NAME is defined.  So, the code between #ifdef and #endif is executed. Similarly, the code between #ifndef and #endif is executed as the macro VAL is not defined. Previous Next

#if, #elif, #else and #endif example

#if If the resultant value of the arithmetic expression is non-zero, then the code between #if and #endif will be compiled. Example: #if 10 > 5      printf("10 is greater than 5"); #endif The code between #if and #endif will be compiled since the resultant value of the expression(10 > 5) is non-zero. #elif This provides an alternate expression to evaluate Example: #if 10 < 5      printf("10 is less than 5"); #elif 10 > 5      printf("10 is greater than 5"); #endif The expression at #if directive evaluates to 0.  So, the expression at #elif is evaluated. If it is non-zero, then the code between #elif and #endif will be compiled. #else If the resultant value of the arithmetic expression is false for #if, #ifdef or #ifndef , then the code between #else and #endif will be compiled. Example: #if 10 < 5      printf("10 is less than 5"); #else      printf("10 is greater than 5"); #endif #e...

How to access union members in C

Dot operator is used to access(or assign) the data members of a union variable.  Consider the following example, union value {          int x;          float y; }; union value obj; Here, obj is a union variable of type union value .   x and y are data members of the union value . Let us see how to assign value to or access data members of union using dot operator. obj.x = 10; The above statement assigns value 10 to the data member x of the union variable obj. obj  - object name(union variable name) x     - data member in union value .     - dot operator Example C program to illustrate accessing union members using dot operator #include <stdio.h> union value { int x; float y; }obj; int main() { obj.x = 5; printf("Value of x is %d\n", obj.x); obj.y = 19.22; printf("Value of y is %f\n", obj.y); printf("Value of x is %d\n", obj.x); ...

How to initialize union variables in C

Let us see all possible ways to initialize a union variable.  Please remember that we can access one data member at a time in the case of union. Method 1: union value {      int x;      float y; }; union value obj = {5}; Here, initialization is done after union definition.   5  is assigned to the member  x  of union variable  obj . Method 2: union value {      int x;      float y; }obj = {5}; Here, initialization is done while defining the union.   5  is assigned to the member  x  of union variable  obj . Method 3: union value {      int x;      float y; }; union value obj = {.y = 5.0}; Here, initialization is done after union definition.   5.0  is assigned to the member y  of union variable  obj.   And we have used dot(.) operator for initialization. Method 4: union value {      int x;     ...

Declaration of a union variable in C

Union variable can be declared while defining a union or after defining a union. Let us see how to declare a union variable while defining a union. union book {           char name[32];           int price; }obj; Here, obj is a union variable of type union book and it is declared while defining the union book . Let us see how to declare a union variable after defining a union. union book {           char name[32];           int price; }; union book obj1, obj2; Here, obj1 and obj2 are union variables of type union book .  And they are declared after defining the union book. Union variable declaration example in C #include <stdio.h> #include <string.h> union book { char name[32]; int price; }obj1; // union variable declaration at definition union book obj2; // union variable declaration after definition int main() { strcpy(obj1.name...

Array of unions

We can create array of unions similar to creating array of any primitive data type. Below is the general form of declaration for array of union. union  <union_name>  <array_name>[size]; Consider the following example, union values { int int_val; float float_val; }; union values arr[2]; Here, arr is an array of union which can hold two union elements. Array of union initialization: Let us see how to initialize array of union. union values arr[2] = {{1}, {2}}; The above statement initializes first union member of both the array elements. union values arr[2] = {{.float_val = 1.1}, {.float_val = 2.2}}; The above statement initialized second union member of both the array elements. How to access union members? Now, let us see how to access union members in the array element. arr[0].float_val = 2.2; Dot operator(access operator) is used to access union array element's data member. Note: In union, only one data member will be active at a time. Size of a union i...

Array of structures

We can create array of structures similar to creating array of any primitive data types.   Below is the general form of declaration for array of structure. struct  <structure_name>  <array_name>[SIZE]; Consider the following example struct student { char name[32]; int age, rollno; }; struct student arr[2]; Here, arr is an array of 2 structure elements. Let us see how to initialize an array of structures. Method 1: struct student arr[2] = { {"Tom", 10, 101}, {"Jerry", 11, 102} }; Method 2: strcpy(arr[0].name, "Tom"); arr[0].age = 10; arr[0].rollno = 101; strcpy(arr[1].name, "Jerry"); arr[1].age = 11; arr[1].rollno = 102; Apart from the above, we are allowed to do partial initialization for structure elements in an array. Consider the following, struct student arr[2] = {{"Tom", 10, 101}, {"Jerry"}}; In the above example, we have done partial initialization for second element in the structure array...

Array of characters - Strings

String is a sequence of characters terminated by null character.  Character array can be used to store strings.  Below is the general form of character array declaration. char array_name[size]; Consider the following declaration, char str[100]; Here, str is a character array which has the capacity to store 100 characters or string of length 100 character(99 char + 1 null char). Let us see how to initialize character array.  Basically, character array can be initialized in either of the following ways. char str[6] = {'I', 'N', 'D', 'I', 'A', '\0'}; char str[6] = "INDIA"; char str[]  = {'I', 'N', 'D', 'I', 'A', '\0'}; char str[]  = "INDIA"; Here, all the above statement gives same meaning.  The string "INDIA" is stored inside the array str . When a string is stored in an array in the form of comma delimited characters, then user has to explicitly include null cha...

Multidimensional arrays in C

Multidimensional array is also known as array of arrays.  C allows user to write arrays with one or more dimensions.  An array with more than one dimension is a multi-dimensional array.  Two dimensional array is a simplest form of multidimensional array.  Below is the general form of multidimensional array. data_type  array_name[size1][size2][size3]..[sizeN]; Consider the following example int arr[2][2][2] = {   { {1, 1}, {1, 1} },                                   { {1, 1}, {1, 1} }                               } ;   The above statement shows the declaration and initialization of multidimensional array(3d array).  Total number of elements in an array can be obtained by multiplying the size value in each dimension. int arr[2][2][2]; 2 X 2 X 2 = 8 elements in the array arr And multidim...

Formatted input and output functions in C

The following are built-in functions available in C language which can be used to perform formatted input output operations. Formatted input functions in C: int fscanf(FILE *stream, const char *format, ...) Performs input format conversion.  It reads the input from the stream and does format conversion.  Then, it will assign those converted values to the subsequent arguments of format correspondingly.  And it returns the number of inputs matched and got assigned with values successfully. int scanf(const char *format, ...) scanf() is equivalent to fscanf(stdin, ...) int sscanf(char *str, const char *format) sscanf() is identical to sscanf() except that the inputs are taken from the string str . scanf fscanf sscanf example in C #include <stdio.h> int main() { FILE *fp; int i, age[3], rollno[3]; char name[3][32], str[128] = "13:103:Ram"; fp = fopen("input.txt", "r"); /* input data for student 1 from user */ ...

Character Input and Output functions in C

The following are the built in functions available in C which can be used to to perform character input & output operations. int fgetc(FILE *stream) It reads the next character from the stream and returns the integer(ascii) value of the character read. int fputc(int c, FILE *stream) It writes the character c on the given stream.  Returns the written character on success.  Otherwise, EOF is returned. fgetc and fputc example in C #include <stdio.h> int main() { int ch; /* prints the input data on the output screen */ while ((ch = fgetc(stdin)) != EOF) { //ctrl + D to exit fputc(ch, stdout); } return 0; }   Output:   jp@jp-VirtualBox:~/$ ./a.out   hello world   hello world int getc(FILE *stream); It reads the next character from the given stream. It evaluates the given stream more than one time, if it is a macro.  Returns integer value(ascii) of the character read. int putc(int c, ...