Jun 23, 2015

EXTERN -- wherever u define variables, it will get access to use them

Extern :

All variables we have seen so far have limited scope (the block in which they are declared) within the program. However, in some applications it may be useful to have data which is accessible from within any other file or which remains in existence for the entire execution of the program.

Suppose if a variable is declared in file1 and we want to access the variable in another file2 and file3, then how to access these variables in other files??? Simple, the answer to this is “Extern”.

Extern keyword is used for the global variables that are defined in one file and can be used those variables in other files by using extern keyword.

extern int a;

Let us see an example:

file1.c                                                                 file2.c

#include<stdio.h>              #include<stdio.h>
int main()                     int a=1;
{                              int main()
    extern int a;              {return 0;}
    printf("%d",a);
    return 0;

}

            In this example, the variable ‘a‘ is created and initialized in file2.c and is used in file1.c as external variable. For information on how to compile a program whose source code is split among multiple files, you can simply type the command gcc -o a file1.c file2.c, and run the program with ./a.

·       When you use extern keyword before the global variable declaration, the compiler understands you want to access a variable being  defined in another program or file, and hence not to allocate any memory for this one. Instead, it simply points to the global variable defined in the other file.
  a)
#include <stdio.h>
extern int i;    //extern variable
int main()
{
    printf("%d",i);
    return 0;
}

Output: Compilation error, undefined symbol i.
        
            b)
         #include<stdio.h>
extern int i;
int main()
{
    i = 1;
    return 0;
}

This program throws error in compilation. Because ‘i’ is declared but not defined anywhere. Essentially, the ‘I’ isn’t allocated any memory. In (b), the program is trying to change the value to 1 of a variable that doesn’t exist at all.

·       If the global variables are not initialized then, they are initialized to their default values.
Int – 0 , Float – 0.0, Char - 0 , String – null

#include <stdio.h>
int i; char c; float f; char *str;  
int main()
{
    printf("%d %d %f %s",c,i,f,str);
    return 0;
}
 
Output: 0 0 0.000000 (null)
 
·       If we declare a variable as extern, it means that the definition for that variable is defined somewhere else in the program or in other file. It doesn’t allocate the memory for these variables. It’s just the declaration. So we can declare it as many times as we can. 
 
#include <stdio.h>
extern int i;        //Declaring the variable i.
int i=1;             //Initializing the variable.
extern int i;        //Again declaring the variable i.
int main()
{
    extern int i;     //Again declaring the variable i.
    printf("%d",i);
    return 0;
}
 
Output: 1
 
·        A particular extern variable can be declared many times but we can initialize at only one time. (even outside or inside the function of same program)

#include <stdio.h>
extern int i; //Declaring the variable
int i=25;     //Initializing the variable
int main()
{
    printf("%d",i);
    return 0;
}
int i=20; //Initializing the variable
 
Output: Compilation error: Multiple initialization                 variable i.
 

·         To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables.

#include <stdio.h>
extern int i=1;    //extern variable
int main()
{
    printf("%d",i);
    return 0;
}
 
Output: 1
 
·        We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally.
a)
#include <stdio.h>
int main()
{
    extern int i=1;   // Try to initialize extern variable
                     // locally.
    printf("%d",i);
    return 0;
}
 
Output: Compilation error: Cannot initialize extern variable.
b)
 
#include <stdio.h>
int main()
{
    extern int i;    // Declaration of extern variable i.
    int i=1;         // Try to locally initialization of
                       // extern variable i.
    printf("%d",i);
    return 0;
}
 
Output: Compilation error: Multiple declaration of variable i.


Filed under ,  | 

Jun 17, 2015

Comma -- Lowest priority operator

Comma Operator :
          It is a binary operator (present in between the two operands), mainly used in two ways :
1)    As a separator
2)    As a operator

As a Separator :
          The comma is used to separate the expressions, and as a separator in functional calls and definitions, multiple variable declarations, enum declarations etc, like semicolon is used to separate the statements (i.e. terminate the statements).

int a =5 , b=6;
void fun( a , b );

As a operator :
As a operator, It evaluates its first operand and discards the result, then it evaluates the second operand and returns the value. It has the lowest precedence (priority) of any c operator and has the associativity from left to right.

                    int j ;
                    j = 1, 2, 3;
                    j = (1, 2, 3);

In first statement, assignment operator (=) has high priority as compared to comma. So the expression becomes (j = 1), 2, 3; which implies j =1;

In second statement, bracket has highest priority than any other operator. So comma is executed first.

1, 2 will return 2                    //      left to right associativity
2, 3 will return 3
          Therefore j = 3;

Note :
          Assigning more than one value or initialization of multiple variables at a time will results in compilation errors.

Example:

int a = b = c = 1; and         int j = 1, 2, 3;     results in errors.

int a, b , c;      a = b = c = 1;
int j;       j = 1 , 2 , 3;

·       We know that Comma operator has the lowest precedence as compared to other operators. But in combination of semicolon and comma, then semicolon has lowest precedence.

In expression a , b ; c , d  it can be grouped as (a , b) ; (c , d).

·       Comma operator act as a Sequence point.

int i = 3 , j = 5;
int k;
k = i++, j--;
l = j--, i++;

In the above expressions, order of evaluation is important. Both k, l have different values. Like if we take + operator, then

k = (i++) + (j--);
l = (j--) + (i++);

Here order of evaluation is not important. Both k, l have same values.

·       Sometimes, the use of comma as separator is confused with as operator.

void fun ( a() , b() )       // comma acts as a separator

Here we don’t consider which function is called first, as comma just act as separator and don’t enforce any sequence. ( the standard calling convention is always from right to left).

Example :

printf( “ajay” , “ganesh” );

You may thought that, the answer should be “ganesh” ( left to right associativity). Before evaluating the statement, we have to check whether comma acts as an operator or separator. Here if we consider as an operator, “ ganesh “ has to be printed.

But the output is “ajay”, because it acts as separator in function parameters. (As I mentioned above standard calling convention, parameters are passed from right to left ). In some books, it is also mentioned that “In case of printf statement, once comma is read then it will consider preceding things as variable or values for format specifier”.

·       Comma acts as an operator only in expressions.

int i = 1, j = 2;               // comma acts as a separator

int i;
i = 1, 2;                          // comma acts as a operator

·       Comma can be used to avoid a block and associated braces, as in :

if (x == 1)
{
    y = 2;
    z = 3;
    cout<<y<<z;
}

Using comma’s, the above program is also written as

if (x == 1)
    y = 2, z = 3, cout<<y<<z;

For practice :
1)

          int x = 10;
int y = (x++, ++x);
printf("%d", y);

2)  
            int x=10 , y;
          y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);
            printf ("y = %d\n", y);
            printf ("x = %d\n", x);

3)

            a) return a=1, b=2, c=3;
        b) return (1), 2, 3;
 

4)

          int choice = 2 ;
            switch(choice)
 {
                        case 1,2,1:
                                     printf("\ncase 1");
                                     break;

                        case 1,3,2:
                                     printf("\ncase 2");
                                      break;

                        case 4,5,3:
                                    printf("\ncase 3");
                                    break;
 }

5)

          int x =1 , y =2;
            if ( y > x  , y < x )
                        printf("\n y < x ");
            else
                        printf("\n x < y ");



Filed under  |