Complete c Handbook

download Complete c Handbook

of 35

Transcript of Complete c Handbook

  • 8/7/2019 Complete c Handbook

    1/35

    Complete C Handbook

    What is C ?

    Ans: C is a programming language developed at AT & Ts BELL laboratories of USA in

    1972 and it was designed and written by Dennis Ritchie. It is reliable,simple and easy to

    use thats why C seems to so popular. C wasnt mean to win prizes; it was meant to befriendly and reliable. The following fig-1.1 shows the evolution of C language:

    Created by sukumar Paul

    ALGOLYear: 1960Developed by:

    International committee

    Remarks: Too general

    CPLYear: 1963

    Developed by:Cambridge University

    Remarks: Difficult toimplement, Hard to learn

    BCPLYear:1967

    Developed By: MartinRichards at Cambridge

    Remarks: Too specific and

    less powerful

    BYear:1970

    Developed By: Ken

    Thompson at AT & T

    Remarks: Too specific

    Traditional C

    Year: 1972

    Developed by: DenisRitchie at AT & T

    Remarks: lost generality

    of BCPL and B restored

    1

  • 8/7/2019 Complete c Handbook

    2/35

    Complete C Handbook

    fig-1.1

    What are the different stages involved in the execution of a C source program?

    Ans: There are several steps involved from the stage of writing a c program to the stage ofgetting it executed. Fig-1.2 shows these different stages:

    Fig-1.2

    Created by sukumar Paul

    Hand written program

    C Source Code

    Expanded Source Code

    Object Code

    Executable Code

    Text Editor

    Preprocessor

    Compiler

    Linker

    2

  • 8/7/2019 Complete c Handbook

    3/35

    Complete C Handbook

    What is ANSI C standard?

    Ans: When it became evident that the C programming language was becoming a very

    popular language available on a wide range of computers, a group of concerned individualsmet to propose a standard set of rules for the use of the C programming language. The Group

    represented all sectors of software industry and after many meeting , they finally wrote an

    acceptable standard for C language. It has been accepted by American National standard

    Institute (ANSI) and also by International Standards Organization (ISO). It was not notforced upon any group or user, but since it is so widely accepted it would be economic

    suicide for any compiler writer to refuse to conform to the standard.

    What is compiler?

    Ans: A program can not be run by the computer directly. This is because a computer canunderstand and execute only those programs that are written in machine language. Thus a C

    program has to convert into machine language before execution. A C Compiler translates a C

    program into a machine language program.

    What is Machine Language?

    Ans: The machine language of a computer consists of a set of instructions, each of which

    corresponds to a relatively simple operation such as add two numbers, go to a particular

    instruction and so on. All these instructions are encoded in binary, and they can be executed bythe computer directly.

    What is assembly Language?

    Ans: Assembly language is one step higher than machine language. Here every machine

    language instruction is given by a given symbolic name, so that programs can be written easily

    using these names instead of binary instructions. Assembly language is a low-level language.A large number of instructions must be written in low-level language even for a simple task

    such as computing and printing roots of quadratic equation.

    What is Linker?

    Ans: Previously i have said that a C source program has to convert into machine languagebefore execution. This process actually takes place in two stages: compilingand linking. The

    compiler performs the basic translation from C statements into machine language

    instructions .The output of the compiler is called the object file. The linkercombines different

    object files to produce the actual executable file.

    Why should not the Compiler itself produce the executable file directly?

    Ans: Consider the following program:

    /* hello.cpp Hello World program*/

    #include

    int main(void)

    {

    Created by sukumar Paul 3

  • 8/7/2019 Complete c Handbook

    4/35

    Complete C Handbook

    Printf(Hello World\n);Printf(Bye);

    return(0);}

    When compiler produce itself the executable file ofhello.cpp:

    In this case, the compiler will have to compile not only hello.cpp but also the functionprintf ,

    since the program hello.cpp calls the functionprintf. Since compilation involves a lot of work,

    compiling every function used by the program will increase the time taken by the compilation.

    When Compiler-Linker scheme produce the executable file for hello.cpp:

    To avoid compiling the code for printf everytime a program is compiled , a set of commonfunction (including printf ) are compiled beforehand and the machine language instructions are

    stored in a file, called the library file. In this case, compiler compiles only the program, and the

    linker joins or links the output of the compiler to the library file and this two stages processcreate a stand alone executable file of hello.cpp.

    Here, when hello.cpp is compiled, the output of the compiler consists of the machine

    language instructions, along with the information that a function named printf is called fromthe program. On getting this information from the output of compiler, the linker searches for

    printf in library file. Upon finding the printf in the library, linker modifies the machinelanguage instructions which were generated by compiler.

    What is Preprocessor?

    Ans: Previously I have said how a compiler and linker interact6 each other to give the

    executable file of a C source program. Actually before compiling, a process called

    preprocessing is done on the source code by a program called the preprocessor.

    #includeThis above line is a preprocessor directive. All lines in the program beginning with a hash(#)

    sign are processed by the preprocessor. The #include directive causes the preprocessor to insert

    the stdio.h file into the C source program. When the compiler compiles the program, it sees thecontents of the stdio.h file instead of the preprocessor directive. Preprocessor performs the

    following activities:

    Macro substitution

    Conditional compilation

    Inclusion of named files

    Error generation

    Pragmas

    Predefined names

    What is Trigraph Characters?

    Ans: many non-english keyboard dont support all characters. ANSI C introduces the conceptof trigraph sequences to provide a way to enter the certain character that are not avaible on

    some keyboard. Each trigraph sequence consists of three characters.fig-1.3 shows some

    ANSI C trigraph sequences:

    Created by sukumar Paul 4

  • 8/7/2019 Complete c Handbook

    5/35

    Complete C Handbook

    Fig-1.3

    What is variable and what are the rules for constructing variable names?

    Ans: A variable is a data name that may be used to store a data value. A variable may take

    different values at different times during execution.

    Rules for constructing a variable name:

    1. A variable name is any combination of 1-8 alphabets, digits or underscores.

    2. They must begin with a letter. Some system permits underscore as a first character.

    3. No commas or blanks are allowed within a variable name.

    4. No special symbol other than an underscore can be used in the variable name.5. Uppercase and lowercase are significant. That is TOTAL is not same as total or as Total.

    6. It should not be a keyword.

    7. But keyword may be part of a name. That is int_type is a valid variable name.8. Average_height and Average _weight will be the same variable as only first eight characters

    are recognized by the compiler.

    These are given in the following table:

    Variable names.... Example

    Cannot start with a number 2times

    CAN contain a number elsewhere times2

    Cannot contain any arithmetic operators ... a*b+c

    ... or any special punctuation marks! result'99.

    Cannot be a C keyword while

    Cannot contain a space stupid me

    CAN start with or contain an underscore _who_is_stupidCAN be of mixed cases ThatsRight

    What is escape sequence?

    Created by sukumar Paul

    Trigraph sequence Translation

    1. ??= # Number sign

    2. ??! | Vertical bar

    3. ??- ~ Tilde

    5

  • 8/7/2019 Complete c Handbook

    6/35

    Complete C Handbook

    Ans: C supports some special character constants consisting more than one characters. Thesecharacter combinations are known as escape sequence. The following escape sequences may be

    used:

    New line \n

    Horizontal tab \t

    Vertical tab \v

    Back space \bAudible alert \a

    Backlash \\

    Question mark \?Single Quote \

    Double Quote \

    What is Typedef?

    Ans: C provides a facility called Typedef for creating new data type names. It takes generalform: typedef type identifier; where type refers to the existing data type and identifier

    refers to the new name given to the data type. The may also belongs to the user defined datatype. For example: the declaration

    typedef int integer

    makes the name integer as a synonym for int. The main advantage of typedef is that we can

    create the meaningful data type names for increasing the readability of the program.

    What is storage class and how many types of storage class are there?

    Ans: Storage class specifier inform the compiler how and where to store the variables.There are four storage class in C:

    1. Automatic storage class : The features of this storage class is given below:

    Storage: Memory

    Default initial value: Garbage value

    Scope: Local to the block in which the variable is declared

    Life: Till the control remains within the block in which thevariable is defined

    Keyword: auto

    Application: General purpose

    2. Register storage class: the features of this storage class is given below:

    Storage: CPU registerDefault initial value: Garbage value

    Scope: Local to the block in which it is defined

    Life: Till the control remains within the block in which the

    variable is defined

    Keyword: register

    Application: in case of loop counter

    3. Static storage class: the features of this storage class is given below:

    Created by sukumar Paul 6

  • 8/7/2019 Complete c Handbook

    7/35

  • 8/7/2019 Complete c Handbook

    8/35

    Complete C Handbook

    For example consider the following conditional statement:If(x==10+15 && y

  • 8/7/2019 Complete c Handbook

    9/35

    Global variablesand strings

    Complete C Handbook

    If the output of the above program is in the region of +32 thousands to -32 Thousands, then thecomputer uses 16 bit integers. If the output of the above program is in the region of +2

    thousand million to -2 thousand million, then the compiler uses 32 bit integers.

    Which two characters helps the compiler to determine the difference between

    function header and function prototype?

    Ans: There are some difference between function header and function prototype:

    1.The prototype has a semicolon, but function header has no semicolon:int print_table(int,float,char *);

    2.But the function header has a open brace and has no semicolon:int print_table(int,float char *)

    {

    What is Heap?

    Ans: An executing program is divided into four parts:

    1. Stack: provides storage for local variables, alters size as the program executes

    2. Data Segment: Global variables and strings are stored here and size is fixed3. Code segment: Functions main, printf, scanf, etc. are stored here. Its read-only.

    4. Heap: otherwise known as dynamic memory. The heap is aviable for us to use and mayalter size as the program executes

    A program executing in memory may be represented by the following diagram:

    Why do some people write if(0 == x) instead of if(x == 0)?

    Ans: It is a trick to guard against the common error of writing =>if(x = 0). If you're in the

    habit of writing the constant before the ==, the compiler will complain if you accidentallytype => if(0 = x). Evidently it can be easier for some people to remember to reverse the test

    than to remember to type the doubled = sign. (Of course, the trick only helps when

    comparing to a constant.)

    Created by sukumar Paul

    Main, printf, scanf etc

    Local Variables

    Dynamic Storage

    Code segment (Fixed size and read only)

    Data-segment(Fixed size and partly read-only)

    Stack and variable in size

    Heap and Variable in size

    9

  • 8/7/2019 Complete c Handbook

    10/35

    Complete C Handbook

    When I set a float variable to, say, 3.1, why is printf printing

    it as 3.0999999?

    Ans: Most computers use base 2 for floating-point numbers as well as for integers. It is well-

    known that in base 10, a fraction like 1/3=0.33333333repeats infinitely. In base 2,

    one divided by ten is an infinitely-repeating fraction (0.0001100110011...), so fractions

    such as 3.1 (which look like they can be exactly represented in decimal) can not berepresented exactly in binary. Depending on how carefully the compiler's

    binary/decimal conversion routines (such as those used by printf) have been written.

    What is the difference between char a[] and char *a?

    Ans: The array declaration char [6] request that the space for 6 characters be set aside ,to beknown by the name by a. That is there is a location named a at which six characters can sit.

    The pointer declaration char *p, on the other hand, request a place that holds a pointer, to be

    known by the name p.The declarations char a[]=Hello; and char *p=world; would initialize the data

    structure that could be represented like this:

    It is important to realize that a reference like x[3] generates different code b, depending on

    whether x is an array or pointer. When compiler will see a[3], it emits code to start at locationa, move three past it, and fetch the character there. When it sees the expression p[3], it emits

    to start at location p, fetch the pointer value there, add three to the pointer, and finally fetch

    the character pointed to. In our example, both a[3] and p[3] happen to be the character l, butthe compiler gets there differently.

    What are the four basic constants in C?

    Ans: A constant doesnt change its value during the entire execution of the program. There

    are four types of constants:

    1. integer constant: integer constant can be specified in three ways:a) Ordinary decimal numbers(base 10): For example: 102

    b) Octal numbers(base 8): For example: 0175. Octal numbers are specified with a

    leading zero, rest of the digit consists of those lying between 0 to 7. here 0175Is equivalent to 125 in decimal(base 10).

    c)Hexadecimal numbers(base 16): For example: 0x175. Hexadecimal numbers are

    specified with 0x or 0X the beginning. The digit that follow 0x must be numbers inthe range 0-9 or one of the letters a-f or A-F . here 0x175 and 0X175 is equivalent to

    Created by sukumar Paul

    H e l l o \0

    w o l d \0p

    10

  • 8/7/2019 Complete c Handbook

    11/35

    Complete C Handbook

    373 in decimal(base 10), and both are same i.e either a lower case or upper case x canbe used.

    2. Floating point constant: Floating point constant have a decimal point or an exponential

    sign or both.a)Decimal notation: for example: 175.52

    b)Exponential notation: Exponential notation is useful in representing

    numbers whose magnitude are very small or very large. The exponential

    notation consists o a mantissa and an exponent. The part appearing before eis called mantissa and the part following e is called exponent. The number

    231.78 can be represented as 0.23178e3.

    3. Character constant: A character constant is either a single alphabet, a single digit, asingle

    Special symbol enclosed within single inverted commas. The maximum length of character

    constant can be 1 character. For example: A, = etc.4. Enumeration constant: enumeration is a user-defined data type that provide by ANSI

    standard. For example: enum color {red,blue,green}; defines color as a new type having

    three values red, blue and green. Each of these are enumeration constants. The identifiers red,blue, green represented the consecutive integer values 0, 1 and 2 respectively. So

    color C;C=blue;

    Printf(As an int , C has the value= %d,C);Will print: As an int , C has the value=1

    Constant values can be explicitly specified for the identifiers. When the value of one

    identifier is specified in this manner, the value of the next element is the next higher integer.For example : enum color {red=10,blue,green=20} ;

    Then the statement c=red will assign 10 to c and c=blue will assign 11 to c. Enumeration are

    a convenient way to associated constant integer in meaningful names.

    What is library function and user-defined function?

    Ans: We have already used printf and scanf function. These functions have already beenwritten, compiled and placed in libraries and are called library function. There are severallibrary functions.

    In case of user-defined function, user has a freedom to choose the function name, return

    data type and the arguments(number and type) are called user-defined function.One of the greatest feature of C is that there is no conceptual difference between the user-

    defined functions and library functions. For example we can write a series of functions to

    process matrices(such as finding inverse, calculating the determinant, etc.). These are user-defined functions because they are written by user. Later they can be compiled into libraries

    and distributed. These functions will act as the library functions. That is, these functions are

    pre-defined and pre-compiled; the user need not worry about how the functions work

    internally.

    What actually does the exit function?

    Ans: Actually exit function terminates a program.

    Syntax: void exit(int status);

    Return type: None

    Description: The function exit terminates the calling process. Before termination, all files are

    closed, buffered output(waiting to be output) is written and any registered function (posted

    with atexit) is called. Status is provided for calling process as the exit status of the process.

    Created by sukumar Paul 11

  • 8/7/2019 Complete c Handbook

    12/35

    Complete C Handbook

    Typically a 0 is used to indicate a normal exit, and a non-zero value indicates an error. One ofthe following can be passed to the function exit:

    EXIT_SUCCESS : normal program termination

    EXIT_FAILURE : abnormal program termination; signal to operating system that theprogram terminated with an error.

    What is atexitfunction?

    Ans: Actually atexit function registers an exit function.Syntax: int atexit(atexit_t func);

    Return value: the function atexit returns 0 on success, a non-zero on failure.Description: The function atexit registers the function pointed to by func as an exit function.

    Each call to atexit registers another exit function. A maximum of 32 function can be registered.

    They are executed on a last-in-first-out basis(the last function registered is the first to be

    executed).Example:

    #include

    #include

    void exit_fn1(void){

    printf("Exit function #1 called\n");

    }

    void exit_fn2(void)

    {

    printf("Exit function #2 called\n");

    }

    int main(void)

    {/* post exit function #1 */

    atexit(exit_fn1);

    /* post exit function #2 */atexit(exit_fn2);

    return 0;

    }

    What is sizeof operator? Write a user-defined function for sizeof operator?

    Ans: The sizeof operator yields the number of bytes required to store an object of the type.

    The name of the variable type is passed to the sizeof operator in closed parentheses. The sizeof

    operator is very useful in developing portable programs. It is very bad practice to assume thesize of a particular type since its size vary from compiler to compiler. The sizeof also takes

    variable names and returns the size of the variable given in bytes.

    Here is a program to clear about sizeof operator:

    #include

    #includevoid main() //sizeof() is a operator not a function

    {

    Created by sukumar Paul 12

  • 8/7/2019 Complete c Handbook

    13/35

    Complete C Handbook

    char a[]="Visual C++";char *b="Visual C++";

    int we[]={5,4,3,2,1};

    clrscr();printf("\n\n\t%d...%d...%d...%d",sizeof(a),sizeof(b),sizeof(*a),sizeof(*b));

    printf("\n\n\t...%d..%d",sizeof(we),sizeof(*we));

    printf("\n\n\t....%d..%d..%d..%d",sizeof(NULL),sizeof(""),sizeof(" "),sizeof(' '));

    getch();}

    Output:

    11...2...1...1

    ...10..2

    ....2..1..2..1A program to implement the sizeof operator:

    #include

    #include #include

    /* Find the size of an variable */

    #define sizeof_var( var ) ((size_t)(&(var)+1)-(size_t)(&(var)))/* Find the size of a data type */

    #define sizeof_type( type ) (size_t)((type*)1000 + 1 )-(size_t)((type*)1000)

    int main (void){

    int a;

    int b[10];clrscr();printf ( "%lu\n", sizeof ( b ) );

    printf ( "%lu\n", sizeof ( b+0 ) );

    printf ( "%lu\n", sizeof_var ( b ) );printf ( "%lu\n", sizeof_type ( int ) );

    return (EXIT_SUCCESS);

    }

    What are macros? What are the advantages and disadvantages?

    Ans: A macro definition or macro has the form :

    #define name(macro template) replacement text(macro expansion)It calls for a macro substitution of the simplest kind subsequent occurrences of token name

    will be replaced by by the replacement text i.e. it goes through the entire program in search ofthe macro template with the appropriate macro expansion. Only after this procedure has been

    completed is the program handed over to the compiler.

    The macro replacement process is influenced by two special operator. One is # symbol andthe other is ## symbol. The # symbol places double quotes around the macro argument

    following it. For example, the following macro defines an easier method instead of printf

    statement, to print single strings.

    Created by sukumar Paul 13

  • 8/7/2019 Complete c Handbook

    14/35

    Complete C Handbook

    #define p(str) printf(#str)After this statement

    P(Sukumar);

    Will translate toPrintf(Sukumar);

    Note that here preprocessor has added the quotes around the macro argument.

    The definition :

    #define p(str) printf(Sukumar)Would not work, since the identifier inside the quotes is not substitute.

    The ## operator concatenates two argument passed to it. Here is an example:

    #include

    #define f(g,g2) g##g2

    void main(){

    int var1314=200;

    printf("%d \t%d",f(var,1314),var);}

    Advantages:Now a million dollar question .why actually c programmer uses macro? Actually macro

    increases the readability of the program. But there is perhaps another important reason forusing macro definition. Suppose a constant like 3.1415 appears many times in our program.

    This value may have to be changed some day to 3.141592. ordinarily we have to go through

    the program and manually change the each occurrence of the constant. However if we definedPI in a #define directive, we need to only one change, in the #define directive itself:

    #define PI 3.141592

    Disadvantages: It makes the program larger. If we use a macro 100 times in a program, themacro expansion goes into our source code at 100 different places, thus increasing the program

    size.

    What is the difference between #include and #includefilename?

    Ans: Actually there exists two ways to write #include statement. These are

    1.#includefilename : if the filename is quoted, searching for the file typically begins wherethe source program was found i.e. the above command look for file in the current directory as

    well as the specified list of directories as mentioned in the include search path that might have

    been set up.

    2.#include : if the filename is enclosed in < and > then the above command willsearch for the file in the specified list of directories only.

    What are differences between macro and function?

    Ans: There are some differences between macro and function:1. In case of macro call, the preprocessor replaces the macro template with its macro

    expansion, in a stupid, unthinking, literal way. Where as in a function call the control is passed to a

    function along with certain argument, some calculations are performed in the functions and auseful value is returned back from the function.

    2. macro makes the program run faster but increases the program size.

    But function makes the program smaller and slow down the execution time.3. macro doesnt return any value. But function return useful value.

    4. Here is a program to show the difference:

    Created by sukumar Paul 14

  • 8/7/2019 Complete c Handbook

    15/35

    Complete C Handbook

    #include#define SQUARE(n) n*n

    int sq(int);

    void main(){

    int j;

    j=4*SQUARE(4+1);

    clrscr();printf("\n\t%d",j);

    j=4*sq(4+1);

    printf("\t%d",j);}

    int sq(int x)

    {return(x*x);

    }

    Output: 21 100

    What is the purpose of const?Ans: sometimes we may like the value of the certain variables to remain constant duringexecution of the program. We can achieve this by declaring the variable with the qualifier

    const at the time of initialization. Example: const int class_room_no=50;

    const is a new data type qualifier defined by ANSI standard. This tells the compiler that thevalue of the int variable class_room_no must not be modified by the program.

    What are the rules for evaluation of expression?

    Ans: 1. First parenthesized sub expression from left to right are evaluated.

    2. If parentheses are nested , the evaluation begins with the inner-most sub expression.3. The precedence rule is applied in determining the order of the application of operators

    in evaluating sub-expression.

    4. The associativity rule is applied when two or more operators of the same precedenceappear in a sub-expression.

    5. Arithmetic expression are evaluated from left to right using the rules of precedence.

    6. When the parentheses are used, the expressions within parentheses assume higher

    priority.

    How can you enable scanf to read a string with spaces?

    Ans: We know that %s specifier can not be used to read string with blank spaces. But this can

    be done with the following %[ ] specification. Blank spaces may be included in the brakets,

    thus enabling the scanf to read string with spaces.Note: Some version of scanf support the following conversion specification for string.

    %[characters] and %[^characters]Here the specification %[characters] means that only the characters specified within the

    brackets are permissible in the input string. If the input string contains any other character, thestring will be terminated at the first encounter of such character.

    The specification does exactly the reverse. That is the character specified after ^ are not

    permitted in the input string. The reading of the string will be terminated at the encounter ofone of these characters. For example:

    #include

    Created by sukumar Paul 15

  • 8/7/2019 Complete c Handbook

    16/35

    Complete C Handbook

    #includevoid main()

    {

    char str1[20],str2[20];scanf("%[^\n]",str1);

    printf("\n%s",str1);

    scanf("%[a-z,' ',A-Z]",str2);

    printf("\n%s",str2);getch();

    }

    Output: Sukumar PAUL

    Sukumar PAUL

    SUKUMAR paulSUKUMAR paul

    What is ternary operator? Write a program to get the greatest number among three

    numbers using ternary operator?

    Ans: The C language has an unusual operator, useful for making two-way decision. Thegeneral form of this operator is:

    expression1 ? expression2 : expression3;

    The above statement says that: ifexpression1 is true, then the value returned will beexpression2 otherwise the value returned will be expression3.

    /*a program calculate greatest value among three numbers using ternary operator*/

    #include

    int main(){

    int a=1,b=17,c=-2,d;

    d = (a>b)?((a>c)?a:c):((b>c)?b:c);printf(Greatest number is= %d,d) ;

    return(0);

    }

    Why do we need a terminating null character in a string?

    Ans: a string is not a data type in C, but it is considered a data structure stored in an array. Thestring is a variable length of structure and is stored in a fixed length array. The array size is not

    always the size of the string and most often it is much larger than the string stored in it.

    Therefore the last element of the array can not always represent the end of the string. So we

    need some way to determine the end of the string data and the null character serves as theend-of-string marker. The terminating null(\0) is important because it the only way the

    function that work with a string can know where the stri8ng ends. Actually, a string not

    terminated by a \0 is not really a string, but a collection of characters.

    What is array of pointer?

    Ans: The way there can be a array of int array of floats, similarly there can be an array of

    pointers. Since the pointer variable always contains an address , an array of pointer would be

    Created by sukumar Paul 16

  • 8/7/2019 Complete c Handbook

    17/35

    Complete C Handbook

    nothing but a collection addresses. The address present in array of pointer can be address ofisolated variables or address of array elements. All the rules apply to an ordinary array is also

    Applicable for array of pointers. For example:

    #includeint main()

    {

    int *arr[4]; /*array of integer pointers*/

    int a=10,b=33,c=98,d=59,i=0;arr[0]=&a; arr[1]=&b; arr[2]=&c; arr[3]=&d;

    for(;i

  • 8/7/2019 Complete c Handbook

    18/35

    Complete C Handbook

    Ans: A memory leak is an allocated memory that is no longer needed but is not deallocated.

    Why i++ execute faster than i+1?

    Ans: The expression i++ requires a single machine instruction such as INR to carry out theincrement operation, whereas i+1 requires more instruction to carry out this operation.

    What is Dangling Pointer?

    Ans: A dangling pointer arises when we use the address of an object after its lifetime is over.This may occur in situations like returning address of the automatic variable from a function

    or using the address of the memory block after it i8s freed.

    What are the files which are automatically opened when a c file is executed?

    Ans: stdin, stdout, stderr (standard input, standard output, standard error)

    What is difference between the structure and union?

    Ans: The difference between structure and union are:

    1. structure allocates the memory equal to the total memory required by the members.But union allocates the memory equal to the maximum memory required by the member

    of the union.

    2. Each member has their own memory space. But in union one block is used by the entiremember of the union.

    What do you mean by void? Can you declare a void type variable?

    Ans: When void used as a function return type, then it means that the function does not return

    any value. For example:

    Void display(char *name){

    printf(Hello %s,name);

    }

    Here display function will not return any value.When void is found in the argument list of the function, then it means that it doesnt take any

    argument. For example:

    int init(void){ return(1);

    }

    Here init function doesnt take any argument but return an integer.

    No, we can not declare any void type variable unlike integer type variable because the sizeof that

    variable is totally unknown to the compiler, so there will be a compiler error.

    What is void pointer?

    Ans: pointers defined to be of a specific data type, can not hold the address of any other type

    variable. It is syntactically incorrect in C to assign the address of, say, an integer variable to apointer of type float. For example:

    float *fprt;

    int i;fptr=&i; /*Compilation Error*/

    An exception to this restriction is a general purpose pointer type called void pointer. The

    format for declaring a void pointer is as: void *v_ptr;

    Created by sukumar Paul 18

  • 8/7/2019 Complete c Handbook

    19/35

    Complete C Handbook

    Pointers declared in this manner do not have any type associated with them and can containaddress of any type of variable. For example:

    Void *v_ptr;

    int i=10;char ch=A;

    float f=2.53;

    v_ptr=&i;

    v_ptr=&ch;v_ptr=&f;

    all the above C statements are correct. But pointers to void can not be directly dereferenced

    like other pointer variables by using * operator. Here is an example:#include

    int main()

    { int i=100;Void *ptr;

    ptr=&i;

    printf(i contains= %d,*(int *)ptr);return(0);

    }Output: i contains= 100

    What do you mean by dynamic memory allocation?

    Ans: Arrays are the most commonly used data structure for storage. The main disadvantage isthat it is a static data structure. During the compilation of the program the array size is

    initialized. Once initialized, they can not grow or shrink in size.

    But in most situation programmer doesnt know that how much memory is needed for the

    program. Thus at the execution time, a program can request more memory. Thus the process ofallocating memory from heap or free memory pool at the time of execution of the program is

    known as dynamic memory allocation. C provides some functions that can be used for

    allocating and freeing memory during program execution. These are malloc, calloc, free,realloc.

    What is malloc, calloc, free, realloc?

    Ans: malloc: The function most commonly used for dynamic memory allocation is malloc(). Ablock of memory may be allocated by the function malloc(). The malloc function reserves a

    block of memory of specified size and returns a pointer of type void. This means we can assign

    it to any type of pointer. It takes the following form:Ptr=(cast-type *) malloc(byte-size);

    For example:

    X=(int *) malloc(100*sizeof(int));

    On successful execution of this above statement a memory space equivalent to 100 times thesize of an int bytes is reserved and the address of the first byte of the memory allocated is

    assigned to the pointer X of type int. If there is not enough space, a NULL pointer is returned.

    Calloc: calloc is a another memory allocation function that is normally used for requesting

    memory space at run time for storing derived data types. While malloc allocates a single block

    of memory, calloc allocates multiple block of memory, each of same size, and then set allbytes to zero. The general form of calloc is:

    Ptr=(cast-type *)calloc(n,element-size) ;

    Created by sukumar Paul 19

  • 8/7/2019 Complete c Handbook

    20/35

    Complete C Handbook

    The above statement allocates contiguous space for n blocks, each of size element-size bytes.All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned.

    If there is not enough space, a NULL pointer is returned.

    Free: Compile time storage of a variable is allocated and released by the system in accordance

    with its storage class. But with the dynamic run-time allocation , it is our responsibility to

    release the space when it is not required. We may use free() function for this purpose:

    Free(ptr);Here ptr is a pointer to a memory block which has already been created by malloc or calloc.

    use of an invalid pointer in the call may create problems and cause system crash.

    Realloc: if we discover later that the previously allocated memory is not sufficient and we

    need to additional space for more elements or the previously allocated memory is much larger

    than necessary and we want to reduce it, in both these cases we can change the memory size bythe function realloc(). For example: if the original allocation is done by the statement:

    Ptr=(cast-type *) malloc(size);

    Then reallocation of space may be done by the statement:Ptr=realloc(ptr,new-size);

    In case, it is not able to find additional space in the same region, it will create the same in anentirely new region and move the contents of the old block into the new block. The functions

    guarantees that the old data will remain intact. But if the function unsuccessful in allocatingadditional space, it returns a NULL pointer and the original block is lost or freed.

    What types of variable does not have address?

    Ans: every type of variable, with the exception of register, has an address.

    What do you mean by pointer to a function?

    Ans: A function, like a variable has an address in memory. It is therefore possible to declare a

    pointer to function, which can be used as an argument in another function. The general syntax

    of declaring a pointer to a function is:Return-type (* pointer-variable) (functions argument list);

    The address of a function can be obtained by only specifying the name of the function without

    the trailing parentheses. If a function is declared as add() then add is the address of the function

    add(). Hence to pass the address of a function, it is sufficient to pass the name of the function.The address of the function can be assigned to pointer variables just like assigning address of

    variables to the corresponding pointer variable. Now let us see using the address of function we

    can manage to invoke it:/*invoking function using pointer to a function*/

    #include

    #include

    void fun1(int,float);void fun2(char *);

    void main()

    {void (*ptr1)(int,float);

    void (*ptr2)(char *);

    int i=10;float f=2.563;

    char ch[]="sukumar";

    Created by sukumar Paul 20

  • 8/7/2019 Complete c Handbook

    21/35

    Complete C Handbook

    clrscr();ptr1=fun1; //assign address of function fun1

    ptr2=fun2; //assign address of function fun2

    printf("\nAddress of fun1=%u",fun1);printf("\nAddress of fun2=%u",fun2);

    ptr1(i,f); //invoke the function fun1

    ptr2(ch); //invoke the function fun2

    fun1(i,f);fun2(ch);

    getch();

    }void fun1(int i,float f)

    {

    printf("\ni=%d.....f=%f",i,f);}

    void fun2(char *ch)

    {printf("\n%s",ch);

    }Output:

    Address of fun1=797Address of fun2=828

    i=10.....f=2.563000

    sukumari=10.....f=2.563000

    sukumar

    pointer to a function is actually used :1. in writing memory resident program

    2. in writing viruses or vaccines to remove the virus

    3. in vc++ programming to connect events to function calls

    What do you mea by dereferencing of pointer? What is indirection operator?

    Ans: Dereferencing is an operation performed to access and manipulate data contained in thememory location pointed to by a pointer.

    The operator * is used to dereference pointers. A pointer variable is dereferenced, when the

    unary operator *, in this case called the indirection operator, is used as a prefix to the pointer

    variable. Any operation performed on the dereferenced pointer directly affects the value of thevariable it points to.

    What is dot operator and what is Arrow operator?

    Ans: let us have a look at the following program:#include

    #include

    void main(){ struct book

    { char name[25];

    char author[25];int callno;

    };

    Created by sukumar Paul 21

  • 8/7/2019 Complete c Handbook

    22/35

    Complete C Handbook

    struct book b1={C handbook,Gordon,105};struct book *ptr;

    ptr=&b1;

    printf(%s %s %d\n,b1.name,b1.author,b1.callno); printf(%s %s %d\n,ptr->name,ptr->author,ptr->callno);

    getch();

    }

    Here we cant use ptr.name or ptr.author because ptr is not a structure variable but a pointer to

    a structure, and the dot operator requires a structure variable on its left. In such cases C

    provides an arrow operator to refer to the structure elements.On the left hand side of the . Structure operator, there must always be a structure variable,

    whereas on the left hand side of the -> operator, there must always be a pointer to structure.

    What is the difference between const char *p, char const *p and char * const p?

    Ans: The first two are interchangeable; they declare a pointer to a constant character (which

    means that we cant change the character). On the other hand, char * const p declares aconstant pointer to a character (i.e. we cant change the pointer).

    Is char a[3]=abc; legal? What does it mean?

    Ans: It is legal in ANSI C (perhaps in some pre-ANSI C systems) but is useful in rare

    circumstances. It declares a array of size 3, initialized with the three character a, b, c,

    without the usual terminating \0(NULL) character. The array is therefore not a true C string,

    and can not be used with strcpy, printfs %s format etc.

    Why cant we perform arithmetic on a void * pointer?

    Ans: The compiler doesnt know the size of the pointed-to objects. Therefore arithmetic onvoid * is disallowed. Before performing arithmetic, convert the pointer to either char * or to the

    pointer type we are trying to manipulate.

    How do you write a program that produces its own source code as its output?

    Ans: consider the following self-reproducing program:

    #includechar *s="char *s=%c%s%c;void main() {printf(s,34,s,34);}";

    void main(){printf(s,34,s,34);}

    What do you mean the by scope of a variable?

    Ans: Scope of a variable can be defined as the region over which the variable is accessible. To

    get an idea about the scope of a declaration, consider the following program:

    #include

    void main(){

    int i=10;printf(I is variable in main and value is= %d,i);

    func();

    j=30; //will give compilation error}

    void func()

    {

    Created by sukumar Paul 22

  • 8/7/2019 Complete c Handbook

    23/35

    Complete C Handbook

    int j=20;printf(j is the variable in func and value is= %d,j);

    }

    Here the statement i=10; , present inside the main, declares i to be an integer variable andinitializes its value to 10. similarly the statement int j=20; is contained inside the function func

    and declares j to be an integer variable with its value initialized to 20. but if we try to compile

    that program the statement in main will cause error. This is because j has not been declared in

    main and the declaration of j in func is not visible in main. Thus we say that scope of j is isrestricted in func.

    What is the use of scope resolution operator?

    Ans: when both global and local variable have the same name, a statement using that name will

    access the local variable(i.e it will access the variable of that name in the innermost block

    containing the statement).The scope resolution operator ::(a double colon) can be used to select the global variable

    explicitly. Consider the following program:

    #includeint i=20;

    void main(){ int i=30;

    printf(i=%d\ti=%d,i,::i);

    }

    Output: i=30 i=20

    What is recursion? Compute the factorial of a given number using recursion.

    Ans: When a called function in turn calls another function a process of chaining occurs.

    Recursion is a special case of this process, where a function calls itself.Recursive function can be effectively used to solve problems where solution is expressed in

    terms of successively applying the same solution to subsets of the problem. When we write a

    recursive function, we must have an if statement somewhere to force the function to returnwithout the recursive call being executed. Otherwise the function will never return.

    //a program to compute the factorial value of a number

    #includelong fact(unsigned int );

    void main()

    {unsigned int n;

    printf(Enter an number: );

    scanf(%u,&n);

    printf(Factorial of %u is= %li,n,fact(n));}

    long fact(unsigned int num)

    {long fact=1;

    unsigned int i;

    for(i=num;i>1;i--)fact*=i;

    return(fact);

    Created by sukumar Paul 23

  • 8/7/2019 Complete c Handbook

    24/35

    Complete C Handbook

    }

    What constant pointer? What is pointer to constant?

    Ans: constant pointer: the declarationint * const pi=i;

    declares a constant pointer to an integer (assume that i an integer array). In this case: *pi=10;

    is perfectly valid, but others which modify the pointer, such as: pi++; are invalid, and result

    the compilation error.Pointer to constant: consider the following declaration :

    Const int * pi;The statement declares pi a pointer to a constant integer. Let pi be initialized by the statement:

    int i[20] ;

    pi=i;

    In this case: *pi=10; or pi[10]=20; are not valid. But pi itself can be changed such as: pi++; areperfectly valid.

    What are bit fields? How they are useful?

    Ans: If in a program a variable is to take only two values 1 and 0, we really need only a single

    bit to store it. Similarly if a variable is to take values from 0 to 3, then two bits are sufficient tostore these values. So why we are wasting an entire integer when one or two or three bits willdo? Because, there are not available one bit or two bit or three bit data type in C. However

    when there are several variables whose maximum values are small enough to pack into a single

    memory location, we can use bit fields to store several values in a single integer. Let us

    consider the following example:#include

    #define MALE 0

    #define FEMALE 1#define SINGLE 0

    #define MARRIED 1

    #define DIVORCED 2#define WIDOWED 3

    void main()

    {

    struct employee{ unsigned gender:1;

    unsigned mar_stat:2;

    unsigned hobby:3;unsigned scheme:4;

    };

    struct employee e;

    e.gender=MALE;e.mar_stat=DIVORCED;

    e.hobby=5;

    e.scheme=9;

    printf("\nGender=%d\nMarital status=%d"

    "\nBytes occupied by e=%d",e.gender,e.mar_stat,sizeof(e));}

    Output: Gender=0

    Created by sukumar Paul 24

  • 8/7/2019 Complete c Handbook

    25/35

    Complete C Handbook

    Marital status=2Bytes occupied by e=2

    In the above example, the colon(within the struct declaration) tells the compiler that we are

    talking about bit fields and the number after it tells how many bits to allot for the field. Herewe have packed all the information about an employee into a single integer(10 bits), since an

    integer 16 bits long.

    Classify the library functions available for I/O?There are numerous number of functions available for I/O. These can be classified into three

    broad categories:1. Console I/O functions: Functions to receive input from keyboard and write output to VDU.

    Console I/O can be further classified into two categories:

    a) formatted console I/O functions: By these function we can read input or display output

    on VDU as per our requirement. For example: printf(), scanf().b)unformatted console I/O functions: We can not read input or display output as per our

    requirement by these function. For example: getch(), getche(), getchar(), putchar(),

    putch(),puts(), gets().2. Disk I/O functions: Functions to perform I/O operations on a floppy disk or hard disk. For

    example: fputc(), fprintf(), fscanf(), etc.3. Port I/O functions: Functions to perform I/O operations on various ports

    What if File? Explain the concept of file.

    Ans: A File is a space on the disk where a group of related data is stored.

    We have seen that console oriented I/O functions, such as printf(), scdanf() can be used

    to read input from keyboard and write output to VDU. These process is fine as long as data is

    small. However in real life problems involve large volumes of data, in such situation two majorproblems occur for using console I/O functions are:

    1. it becomes time consuming to handle large volumes of data through terminals.

    2. The entire data is lost when either program is terminated or the computer is turned off.It is therefore necessary to have more flexible approach where data can be stored on the disks

    and read when necessary, without destroying the data. This method employs the concept of

    files to store data.

    What is the use of fflush(stdin)? Explain with an example.

    Ans: consider the following example:

    #include#include

    void main()

    { FILE *fp;

    char another=y;char name[40];

    int age; float bs;fp=fopen(EMPLOYEE.TXT,w);

    if(fp==NULL)

    {

    puts(Can not Open file);exit();

    }

    Created by sukumar Paul 25

  • 8/7/2019 Complete c Handbook

    26/35

    Complete C Handbook

    while(another==y){ printf(enter the name ,age and basic salary: \n);

    scanf(%s%d%f,name,&age,&bs);

    fprintf(fp,%s%d%f\n,name,&age,&bs);printf(Another employee?(Y/N));

    fflush(stdin);

    another=getche();

    }fclose(fp);

    }

    In the above program we have used fflush(stdin), to get rid of a peculiarity of scanf(). Aftersupplying data for one employee, we would hit the enter key. What scanf() does is it assign

    name, age and salary to appropriate variables and keeps the enter key unread in the keyboard

    buffer. So when its time to supply Y/N for the question, getche will read enter key from thebuffer thinking that user has entered the enter key. To avoid this types of problem we use

    fflush(stdin). It is designed to remove or flush out ant data remaining in the buffer. The

    argument to fflush() must be the buffer which we want to flush out. Here it is stdin, whichmeans buffer related with standard input device the keyboard.

    What is command line argument?

    Ans: command line argument is a parameter supplied to a program when the program is

    invoked. This parameter may represent a filename the program should process. For example if

    we want to execute a program to copy the contents of a file named orig_file, to another onenamed copy_file, then we may use the command line like:

    C>PROGRAM.EXE orig_file copy_file

    Here PROGRAM.EXE is the filename where the executable code of the program is stored.

    Actually, main() can take two arguments called argc and argv and the information contained in

    the command line is passed on to the program through these arguments, when main is called by

    the system.Here the variable argc is an argument counter that counts the no. of arguments on the

    command line. The argv is an array of character pointer that points to the command line

    argument. The size of the array will be equal to the value of argc. For the command line givenabove, argc is 3 and argv is an array of three pointer to strings:

    argv[0] => PROGRAM>EXE

    argv[1] => orig_file

    argv[2] => copy_fileIt is not necessary that we should always use the variable names agrc and argv.

    What is file pointer? Why it is needed?

    Ans: file pointer is nothing but a pointer to a structure. This structure has been typedefed intoFILE in the header file stdio.h. The structure is given below:

    typedef struct {

    short level;unsigned flags;

    char fd;

    unsigned char hold;short bsize;

    unsigned char *buffer, *curp;

    Created by sukumar Paul 26

  • 8/7/2019 Complete c Handbook

    27/35

  • 8/7/2019 Complete c Handbook

    28/35

    Complete C Handbook

    Created by sukumar Paul 28

  • 8/7/2019 Complete c Handbook

    29/35

    Complete C Handbook

    Created by sukumar Paul 29

  • 8/7/2019 Complete c Handbook

    30/35

    Complete C Handbook

    Created by sukumar Paul 30

  • 8/7/2019 Complete c Handbook

    31/35

    Complete C Handbook

    Created by sukumar Paul 31

  • 8/7/2019 Complete c Handbook

    32/35

    Complete C Handbook

    Created by sukumar Paul 32

  • 8/7/2019 Complete c Handbook

    33/35

    Complete C Handbook

    Created by sukumar Paul 33

  • 8/7/2019 Complete c Handbook

    34/35

    Complete C Handbook

    Created by sukumar Paul 34

  • 8/7/2019 Complete c Handbook

    35/35

    Complete C Handbook