Sunday, 30 September 2018

Variable Argument List Function

  
A function that can accept any number of arguments, means number of arguments are not predefined that is a variable argument list function . In a typical function we can only pass a fix number of arguments while calling.

For exp:-


Above is the gcc screenshot of a fixed argument function sum(), sum is a user defined function that can accept only two arguments. If we call sum() with more than two or less then two argument then it will generate Linker error.

We cannot call sum as sum(a,b,c).While doing so compiler generates error as below :-



Question is can we create our own function like printf(),scanf() that have no fixed number of arg.
*Can we create our own sum() function** which can accept n number of arguments ?
We can achieve this by using Variable length argument feature.


How to do that ? :-

******************************************************************************
Variable argument length(Variable argument list) feature allows the function to receive n number of arguments in a function.

How to define a variable argument function?

There are two ways :-
  1. We can pass a fixed argument that argument indicates how many variable arguments are there.
  2. Pass a null at the end to indicate number of variable arguments.
*********************************************************************************
Irrespective of the two ways.

We define a function using (...) three dots as one of the arguments to indicate its of variable argument length.
Exp:-
int sum(int,...);
int sum(char *n,..);

 -First we will discuss method 1



To understand method one we can undergo linux man page of va_start
cmd$  man va_start


Step 1: Create a variable(pointer similar to char*) of type va_list

va_list v;


Step 2 : Call function va_start to specify total no. of arguments to fetch .

va_start(v,n);

For the above program:
va_start(v,n)  n being the total no. of arguments starting from va_list v.
this value becomes va_start(v,3) for the sum(3,i,j,k) specifying to traverse from va_list v to n .

Step 3: Use va_arg to fetch the values of the type of argument passed as 2nd argument (integer in the case of the above program)

s=s+va_arg(v,int);

For the above program this function is used to fetch the value of all the variable argument ** provided the type of argument
va_arg( v , int ) Integer being the type of argument in function.
Implies function sum(3,i,j,k)  > sum(3,50,60,70) the values of the variable argument list is fetched.

Struct Hack

Blog post is related to structure hacking, its a trick of structure to reduce the size of structure.

We must understand few basic thing before discussing Struct Hack:-

What is char a[0]={'1','2','3','4'};
Its an array but what is the sizeof 'a' and what is the sizeof 'a[0]' .
sizeof(a)        =               0
sizeof(a[0])   =               1

Now :-

struct student
{
int      rollno;
int      name_length;
char   name[0];                             // some compiler provides error so there we can use name[1]
}stdnt;


sizeof stdnt is 4+4+0 = 8 .

When we create an array of zero length then its size is also zero, because size of an array depends upon the index multiplied by the size of type. When we create an array of zero length in structure it must be the last member of structure. This technique is known as "Struct Hack".




 Above is the screenshot of a working gcc program.

Use Of Struct Hack :-

It is use to create variable,according to the required length at run time.

In the above code name_length is not constant for every student, if we use pointer the 4 byte of data for pointer is also added and this is the benefit of Struct Hack. 
















Monday, 24 September 2018

Storage Classes (Register)

Register storage classes are used to stored the local variable in CPU register not in memory.

Default Value :-

  • Default Value of register storage classes is garbage.
  • We can declare it locally
Memory :-

  • Register storage class variable are always stored in CPU register
Scope :-
  •  Scope of register storage class variable is within a block or braces.  
Life :-

  • Life of register is same as an auto storage class.

Important Note  :-

We can not use the address of register storage classes variable because it stored in CPU.
Register storage class is fastest of all four storage type.

Function arguments are of register storage class.




Wednesday, 5 September 2018

Storage Classes 3 (Extern)

Extern Storage Class :-

Default Value :-

  • Default value of extern variable is zero (0).
  • We can declare global as well as local.

Memory :-

  • It stored in data section
Life :-
  • Life of extern variable start when program is loaded and end when program is execution completed.
Scope :- 
  • If we declare variable as global then all the file (which compile at a time) and function we can use easily.
  • If we declare local then we can access within the function only.


Important Note :- 

                           Global variable default an extern storage classes.
                           Default the function are extern but not variable.
                           By using extern we give the information to variable that its declaration may be present in other file.
                           If declaration is not present in other file as well so it will give an error.  

Wednesday, 29 August 2018

Storage Classes 2 (Static)

In this post we will discuss about static, extern and register storage classes.

But first we need understand what is the difference between life and scope :-

Life :-

The lifetime of variable in C language is the time, for which the variable have memory location in memory section. Its may be during the run time execution of the program or while creation or destruction of the function stack.

Scope :- 

The scope of variable in C language is that part of code till which we can directly access the variable. 


Static Storage Classes :-



Default Value :-
  • Default value of static variable is zero(0) or NULL if pointer.
  • We can declare a static variable, global as well as local.
Memory :-

Data section are divided into two things 
  • Initialize data section ( Data )
  • Uninitialized  data section ( BSS-Block started by symbol )
Scope :-

  • If we declared a static variable locally then the scope is within function or block.
  • If we declared a static variable globally then the scope is within that whole file.
Life :-
  • Life of static variable starts when program execution starts till the execution is completed.
Important Note :-
                              Re-initialization is not possible for static variable because life of the variable is up to end of compilation.
                              Global Static variable are having internal linkage. We can access that variable with in the file.

Tuesday, 28 August 2018

Storage Classes 1


Storage Classes are used to describe about the features of a variable. 


Basically there are four things that will decide the storage classes-

  • Default Value
  • Memory (Where it Stored)
  • Scope (Visibility)
  • Life
There are four storage classes in C Language are given bellow -
  1. Auto
  2. Static
  3. Extern
  4. Register 

Auto Storage Classes :- 

Default Value :- 
  • For local variable if we don't specify any storage type, then the compiler will treat that as auto .
  • All auto variable are local variable but we can not say all local variable auto variable.
Memory :-
  • Auto variable are present in function stack frame.
Scope :-
  • Scope of an auto is within a function or within block where it is declared.
Life :-
  • Life of an auto variable start when function execution start and ends when function execution ends.


Important Note :     
                              Re-Initialization is allowed for auto storage class. 
                              We should not catch Auto variable address while returning from the function.




Remaining storage classes will discuss in next post.

Saturday, 21 July 2018

Array

Arrays





An array is a collection of similar data type stored at continuous memory locations.
Variable (Data type) can be int,char,float

Declaration Syntax;
int a[10]; (integer array)
char b[10]; (character array)
int *p[10]; (array of pointer)
int *fptr[10] (int,int);(array of function pointer)






Tuesday, 5 June 2018

Typedef



typedef is a reserved keyword in the C and C++ programming languages. It is used to create an alias name for another data type.



Limitations :-


  • typedef is limited to giving symbolic names to types only, where as #define can be used to define alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc.

  • define should not be terminated with semicolon, but typedef should be terminated with semicolon.

  • typedef follows the scope rule which means if a new type is defined in a scope (inside a function), then the new type name will only be visible till the scope is there.




  • Enum

    An enum is a keyword, it is an user defined data type. All properties of integer are apples to Enum. It is used for creating an user defined data type of integer. Using enum we can create sequence of integer constant value.

    Key Points :


    • With the help of enumeration we can put a name for constant.
    • User readability improves;
    • Default first member value is 0(zero)
    • We cannot increment or decrement.
    Syntax :

    enum { red, black = 5, white, green };


    Union

    A union is a special data type available in C that allows storing different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple purposes.

    Key Points :

    • It is an user defined data type;
    • Union is a collection of different type of memory but not in contiguous form;
    • In union all member will share same location;
    • Size of union depends upon the size of the largest member;
    Syntax :

               union tagname 
                          {
                            member 1;
                            member 2;
                            member 3;
                            .
                            .
                            .
                           };

    STRUCTURE - 3 (Structure padding)


                         

                  "Allocating the memory for a structure variable more then the required memory is called structure padding, that extra byte of memory is called hole in a structure;"






    Some more examples:

    struct A
             {
             int a;
             char c;
             float f;
             };
    Size of struct A should be 9 but it is 12, that is known as structure padding and extra 3 byte are known as hole.

    For removing the hole we can use below keyword:

    #pragma pack(1)   //only in GCC compiler 



    STRUCTURE - 2

    Now we discuss some key features of structure :- 

    Structure Pointer :

                    Pointer size is dependent upon OS ,same applies for structure pointer. we will assume a 32-bit system.

    Exp :

    struct st
             {
              int a;
              char b;
              };
    main()
    {
    struct st a1 ={10, p} , *ST;
    ST = &a1;

    for access :-

    printf("%d %c",ST->a , ST->b );

    Ways to Pass a structure in function :

    1) print1(a1.a, a1.b);
    2) print2(ST);
    3) print3(&a1);

    Structure Bit Field :

    •  Bit field is a mechanism in C-Language where we can allocate a memory in the form of  Bits.
    • Bit field can only be used in Structure and Union.
    struct A
             {
             int a:6;
             chat ch:3;
             };

    Here int take b bit and char take only 3;

    Limitation of bit Field :
    • We cannot allocate more bit size, then the actual size.
    • bit field are applicable only for char and int.
    • Getting address of bit field variable is possible.
      

    Monday, 4 June 2018

    STRUCTURE - 1

    Structure is an user define data type which is collection of different primitive data types.

    Syntax :

    struct tagname
           {
           member 1;
           member 2;
           member 3;
           .
           .
           .
           };



    • tagname is nothing but new data type;
    • Until and unless we create a variable for structure there is no memory allocated for the member;
    • If we want to access the member of structure through structure variable we use dot(.) operator;
    • If we want to access the member of structure through structure pointer, we use arrow (->) operator;

    Limitation of structure :-

    • It is not possible to initialize the member of structure.
    • Storage classes are not allowed for structure members but storage classes are allowed for variable of structure.
    • In a structure we can't declare the same structure type but we can create a same structure pointer. (Self referential structure)
    • Structure within structure is possible but the changed name (using typedef) structure is not possible in that structure.

    User Defined Data Type

    Sometimes, the basic set of data types defined in the C language such as int, float, char, double etc. may not be insufficient for our program. Under such circumstances we can create our own data types based on primary data types


    There are mechanisms for doing this in C:

    Using : typedef

    Using : Stucture
    Using : Union 
    Using : Enum

    They are all known as User as well as Member define data type because user can amend according to their requirement.


    Use Of typedef :-
    The purpose of typedef is to assign alternative names/ alias name to an existing types. Sometime standard declaration is confusing, or likely to vary from one implementation to another.

    Use Of Structure :-
    Structure is data type available in C that allows to combine data items of different kinds. To define a structure, you must use the struct statement. Structure is a collection of variables of different types under a single name.

    Use Of Union :-
    A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. 

    Use Of Enum :-
    Enumeration (or enum) in C. Enum is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. enum State {Working = 1, Failed = 0};


    Note: Next we will discuss about all in detail 

    Wednesday, 24 January 2018

    Control Statement

    A control statement is a statement that determines whether other statements will be executed. An if statement decides which statement to execute, or decides which of two statements to execute.

    In other words "Control Statement is a statement that control the flow of program compilation. "

    "Control Statement are used for spiking some statement for few iteration/time."

    "Are also used for execute the same statement to certain time."




    Non-Iterative:-











    Memory Layout Of a C Program




    After writing a C program this is the first question that comes in our mind.


    • Code Section: This part of memory contains the program code,Its usually read only.
    • Data Section: This section contains all the static,global and extern variables defined by the programmer.
      • BSS(uninitialized data):If we are not initialing the static variable or global variable.Lets say we declare an variable: int i; this is initialized to zero default & stored in this section.
      • Initialized data :If we initialize a global or static variable say int i=10;It is stored in this section. 


    •  Heap Section: Dynamic allocated memory using functions such as calloc() and malloc() is stored in this part of the memory.

    • Stack Section: Whenever a function is called in C program,respectively a function stack frame is created,which is eventually destroyed after the call.This function stack frame is stored in stack section.All auto variable which are declared inside the function becomes the part of this memory section.  

    FAQ in interviews:

    • Why do we need a BSS segment? Can't we just use memset() to clear the memory and use only one segment in data section?
    • Why do we need a heap section?
    • Where will extern int i=10 gets stored?
    • Where are function arguments stored in C?

    Tuesday, 23 January 2018

    Type Casting & Type Qualifier

    Type Casting :-

    Type casting is the way to convert the data from one type to  other type. Exp:- Converting the short int to long int vice versa.


    Type of Type Casting:-
    1. Implicit Type Casting
    2. Explicit Type Casting

    Implicit Type Casting :-

    When Type Casting is performed automatically by the compiler, without programmers intervention, such type of conversion is know as Implicit Type Casting. 

    Exp:-  int a = 10, r;
               short  int b = 20; 
              r = a + b ;
    // in 32bit OS// int size is 4 byte , short int size 2 byte.
    // r and a size is 4 byte and  b size is 2 byte, but when the expression is going to solve the 

    Explicit Type Casting :-

    When Type Casting is performed forcefully by programmers, that is known as Explicit Type Casting .

    Exp:-  Take same example for easy to understand 

              short int a = 10, r;
              int b = 20; 
              r = a + ( short int )b ;

    Monday, 22 January 2018

    Operators In C



    Symbols that are used to perform some operations in a C program are called Operators.



    Operators are categorized as:-

    1. Unary Operator(Uses One Operand)
    2. Secondary Operator(Uses Two Operands)
    3. Ternary Operator (Uses Three Operands)

    Type Of Operators In C  :-

    Ignore Comma, Comma itself an Operator
    • Arithmetic Operators                  (Exp:- +, -, *, /,%  ) 
    • Relational Operators                   (Exp:- >, >=, <=,<, ==, =!)
    • Logical Operators                       (Exp:- &&, || , ! )
    • Assignment Operators                (Exp:- = )
    • Bit Wise Operators                     (Exp:- &, |, ^, ~ )
    • Size Of Operator                        (Exp:-  sizeof()  )
    • Comma Operator                        (Exp:-    ,    )
    • Inc and Dec Operator                 (Exp:- ++, -- )
    • Conditional Operators                (Exp:- condition?true:false  ) 
    • Address Operator                        (Exp:- &(reference operator )  )
    • De-reference Operator                (Exp:- *  )
    Many more are there that will discuss in coming posts.  

    Frequently Ask Questions In Interview :-

    1. Tell us 5 Unary Operators.
    2. Example of Ternary operator. (You should take a situation ; then explain) 







    Tuesday, 16 January 2018

    Data Type

    Variables in C have associated data types. Each data type requires different amounts of memory and has some specific operations which can be performed over it.

    Basically there are two types of data in C :- 

    1. Primary Data Type
    2. Secondary Data Type

    Primary Data Type :- 
              Primary data type is Pre-defined by C itself.
    • int
    • char
    • float 
    • double
    Secondary Data Type :-
             Secondary data type are defined by the help of primary data types.
    • array
    • pointer
    • structure
    • union
    • enum
    • typedef
    Structure, Union, Enum & Typedef are also known as User Defined Data Type.
    In upcoming post we will discuss data types in detail.


    Thursday, 4 January 2018

    Type of errors in C


    Error is an abnormal condition whenever it occurs,execution of program stops,It can be classified as:

    1) Compile time error

    2) Run time error



    1) Compile time error :-


    • Pre-processor error
      Here I missed "i" in first instruction then got error as below













    • Translator 

    Here I missed ";" then got error as below










    • Linker

    2) Run time error :-

    • Segmentation fault
    • Bus Error