DISHA NIRDESHAN

Enlightens your career

Wednesday, June 8, 2011

Basic Questions of C





 What are the features of C? or What is C language ?
The features of 'C' language are:-
1) It is a modular language... i.e. A large problem can be divided into many sub problems(modules) and tnen can be solved individually... Finally with all the solutions ready one can integrate them and find the final solution to that so called large problem...

c-can be used for systems programming and general purpose programs,
applications of c-language
unix operating system(kernal was implemented by c),games,device driver,editor,compiler
very important of c-language is modularity.through which re-usability,

What are the applications and advantages of C-language?
1.'C' is the only intermediate programming language in between low level and high level programming language.

2.All applications written in "C" will be executed fast.

3.All aeronautical applications , mission critical applications are written in "C".

4.Embedded programming is written in "C".

What is the difference between compile time error and run time error?
Compile time is semantic and syntax error, whereas run time is memory allocation error e.g. segmentation fault.If the program has the compile time error then the program wont execute. Eg: syntax or semantic errors.

If the program has the runtime error then the program would compile successfully with no erros. But the out put was not desired.
eg: dividing with zero.

Can you write a c program without using main function?
The compilation process always starts from the first line of your source code and the compiler checks only syntax, if you don't have a main() not at all a problem. But if you want to execute that you need main(). Check how we are going to create a header file are we going to place a main() in a header file.
we can write the code without main() function. The code will gets compiled and during compilation it won't show any error but while executing it show an error saying LINKER ERROR.
What will the preprocessor do for a program?
The C preprocessor is used to modify your program according to the preprocessor directives in your source code. A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code. The preprocessor is invoked as the first part of your compiler program?s compilation step. It is usually hidden from the programmer because it is run automatically by the compiler.

The preprocessor reads in all of your include files and the source code you are compiling and creates a
preprocessed version of your source code. This preprocessed version has all of its macros and constant
symbols replaced by their corresponding code and value assignments. If your source code contains any
conditional preprocessor directives (such as #if), the preprocessor evaluates the condition and modifies your source code accordingly.

preprocessor do:1>macro substitution
2>multiple spaces into one
3>including all header files
4>include all conditional compilations
5>removing the comment lines


What is :- Asembler , compiler , Preprocessor , laxical analysis , parsing ?
Assembler:It converts the assembly language into machine level.
Compiler:It converts the high level program into machine level.
Preprocessor: Already defined using #define and used later in the program.
Lexical analysis:It analyze the expression from left to right and separate into tokens.
Parsing:It groups the token collected from the lexical analyser and constructs parse tree.



Is the c is procedure oriented?
yes, C is procedure oriented language because large program is divided into modules.And it is also called structured oriented language.




 C is a structural or highlevel or middle level language which one is correct answer ?
C is a middle level language.

Because this language contains both the features of both high level language

and low level languages.

Also can be called as structured programming language.






Questions on Functions



What is modular programming?

If a program is large, it is subdivided into a number of smaller programs that are called modules or subprograms. If a complex problem is solved using more modules, this approach is known as modular programming.

 

 

 

 

What are the advantages of the functions?

- Debugging is easier
- It is easier to understand the logic involved in the program
- Testing is easier
- Recursive call is possible
- Irrelevant details in the user point of view are hidden in functions
- Functions are helpful in generalizing the program

 

 

 

What is an argument ? differentiate between formal arguments and actual arguments?

An argument is an entity used to pass the data from calling funtion to the called funtion. Formal arguments are the arguments available in the funtion definition.They are preceded by their own data types.Actual arguments are available in the function call.

Why should I prototype a function?

A function prototype tells the compiler what kind of arguments a function is looking to receive and what kind of return value a function is going to give back. This approach helps the compiler ensure that calls to a function are made correctly and that no erroneous type conversions are taking place.

Is using exit() the same as using return?

No. The exit() function is used to exit your program and return control to the operating system. The return statement is used to return from a function and return control to the calling function. If you issue a return from the main() function, you are essentially returning control to the calling function, which is the operating system. In this case, the return statement and exit() function are similar.

 

Recursion: A function is called 'recursive' if a statement within the body of a function calls the same function. It is also called 'circular definition'. Recursion is thus a process of defining something in terms of itself.

 

Pass by Value: In this method, the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. In pass by value, the changes made to formal arguments in the called function have no effect on the values of actual arguments in the calling function.

 

Pass by Reference: In this method, the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses, we would have an access to the actual arguments and hence we would be able to manipulate them. C does not support Call by reference. But it can be simulated using pointers.

 

Is it better to use a macro or a function?

The answer depends on the situation you are writing code for. Macros have the distinct advantage of being more efficient (and faster) than functions, because their corresponding code is inserted directly into your source code at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function. However, macros are generally small and cannot handle large, complex coding constructs. A function is more suited for this type of situation. Additionally, macros are expanded inline, which means that the code is replicated for each occurrence of a macro. Your code therefore could be somewhat larger when you use macros than if you were to use functions.
Thus, the choice between using a macro and using a function is one of deciding between the tradeoff of faster program speed versus smaller program size. Generally, you should use macros to replace small, repeatable code sections, and you should use functions for larger coding tasks that might require several lines of code.


--
MD.MOHSIN KHAN



--
MD.MOHSIN KHAN

Other concepts


Is it better to use malloc() or calloc()?


Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory at least big enough to hold them all:
void *calloc( size_t numElements, size_t sizeOfElement );
There's one major difference and one minor difference between the two functions. The major difference is that malloc() doesn't initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you're going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you're going to use as a pointer is set to all zero bits. That's usually a null pointer, but it's not guaranteed.Anything you're going to use as a float or double is set to all zero bits; that's a floating-point zero on some types of machines, but not on all.
The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.

 

When is a switch statement better than multiple if statements?

A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric type.

 
 

What is #line used for?


The #line preprocessor directive is used to reset the values of the _ _LINE_ _ and _ _FILE_ _ symbols, respectively. This directive is commonly used in fourth-generation languages that generate C language source files.


What is static memory allocation and dynamic memory allocation?


Static memory allocation: The compiler allocates the required memory space for a declared variable.By using the address of operator,the reserved address is obtained and this address may be assigned to a pointer variable.Since most of the declared variable have static memory,this way of assigning pointer value to a pointer variable is known as static memory allocation. memory is assigned during compilation time.
Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically.If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation.memory is assined during run time.


When would you use a pointer to a function?


Pointers to functions are interesting when you pass them to other functions. A function that takes function pointers says, in effect, Part of what I do can be customized. Give me a pointer to a function, and I'll call it when that part of the job needs to be done. That function can do its part for me. This is known as a callback. It's used a lot in graphical user interface libraries, in which the style of a display is built into the library but the contents of the display are part of the application.
As a simpler example, say you have an array of character pointers (char*s), and you want to sort it by the value of the strings the character pointers point to. The standard qsort() function uses function pointers to perform that task. qsort() takes four arguments,
- a pointer to the beginning of the array,
- the number of elements in the array,
- the size of each array element, and
- a comparison function, and returns an int.

When should a type cast not be used?

A type cast should not be used to override a const or volatile declaration. Overriding these type modifiers can cause the program to fail to run correctly.
A type cast should not be used to turn a pointer to one type of structure or data type into another. In the rare events in which this action is beneficial, using a union to hold the values makes the programmer's intentions clearer.

 

 

 

 

 

What is the easiest searching method to use?

Just as qsort() was the easiest sorting method, because it is part of the standard library, bsearch() is the easiest searching method to use. If the given array is in the sorted order bsearch() is the best method.
Following is the prototype for bsearch():
void *bsearch(const void *key, const void *buf, size_t num, size_t size, int (*comp)(const void *, const void*));
Another simple searching method is a linear search. A linear search is not as fast as bsearch() for searching among a large number of items, but it is adequate for many purposes. A linear search might be the only method available, if the data isn't sorted or can't be accessed randomly. A linear search starts at the beginning and sequentially compares the key to each element in the data set.

 

 

 

  What is a structure?

A structure is a collection of pre-defined data types to create a user-defined data type. Let us say we need to create records of students. Each student has three fields:

int roll_number;

char name[30];

 

int total_marks;

This concept would be particularly useful in grouping data types. You could declare a structure student as:

view source

print?

1

struct student {

2

 int roll_number;

 

3

 char name[30];

4

 int total_marks;

 

5

} student1, student2;

The above snippet of code would declare a structure by name student and it initializes two objects student1, student2. Now these objects and their fields could be accessed by saying student1.
style='font-size:10.0pt;font-family:"Courier New";color:#0000C0'>roll_number for accesing roll number field of student1 object, similarly student2.
style='font-size:10.0pt;font-family:"Courier New";color:#0000C0'>name for accesing name field of student2 object.



What are the advantages of using unions?

Union is a collection of data items of different data types.
It can hold data of only one member at a time though it has members of different data types.

If a union has two members of different data types, they are allocated the same memory. The memory allocated is equal to maximum size of the members. The data is interpreted in bytes depending on which member is being accessed.

Example:

1

union pen {

2

 char name;

 

3

 float point;

4

};

Here name and point are union members. Out of these two variables, 'point' is larger variable which is of float data type and it would need 4 bytes of memory. Therefore 4 bytes space is allocated for both the variables. Both the variables have the same memory location. They are accessed according to their type.
Union is efficient when members of it are not required to be accessed at the same time.

 

 

What is storage class and what are storage variable ?

A storage class is an attribute that changes the behavior of a variable. It controls the lifetime, scope and linkage.
of storage classes
1) auto
2) static
3) extern

4)register

 

What are register variables? What are advantages of using register variables?

Register variables are stored in the CPU registers. Its default value is a garbage value. Scope of a register variable is local to the block in which it is defined. Lifetime is till control remains within the block in which the register variable is defined. Variable stored in a CPU register can always be accessed faster than the one that is stored in memory. Therefore, if a variable is used at many places in a program, it is better to declare its storage class as register

 

Example:
register int x=5;
Variables for loop counters can be declared as register. Note that register keyword may be ignored by some compilers.

 

What is a static function?

A static function is a function whose scope is limited to the current source file. Scope refers to the visibility of a function or variable. If the function or variable is visible outside of the current source file, it is said to have global, or external, scope. If the function or variable is not visible outside of the current source file, it is said to have local, or static, scope.

When should a type cast not be used?

A type cast should not be used to override a const or volatile declaration. Overriding these type modifiers can cause the program to fail to run correctly.
A type cast should not be used to turn a pointer to one type of structure or data type into another. In the rare events in which this action is beneficial, using a union to hold the values makes the programmer's intentions clearer.



What is a macro, and how do you use it?

A macro is a preprocessor directive that provides a mechanism for token replacement in your source code. Macros are created by using the #define statement.
Here is an example of a macro: Macros can also utilize special operators such as the stringizing operator (#) and the concatenation operator (##).The stringizing operator can be used to convert macro parameters to quoted strings, as in the following example:
#define DEBUG_VALUE(v) printf(#v is equal to %d.n, v)
In your program, you can check the value of a variable by invoking the DEBUG_VALUE macro:
...
int x = 20;
DEBUG_VALUE(x);
...
The preceding code prints x is equal to 20. on-screen. This example shows that the stringizing operator used with macros can be a very handy debugging tool.

 

What are header files? Are functions declared or defined in header files ?

Functions and macros are declared in header files. Header files would be included in source files by the compiler at the time of compilation.

Header files are included in source code using #include directive.#include<some.h> includes all the declarations present in the header file 'some.h'.

A header file may contain declarations of sub-routines, functions, macros and also variables which we may want to use in our program. Header files help in reduction of repetitive code.

Syntax of include directive:
#include<stdio.h> //includes the header file stdio.h, standard input output header into the source code

 


What is an Enumeration?

Enumeration is a data type. We can create our own data type and define values that the variable can take. This can help in making program more readable. enum definition is similar to that of a structure.


What is the use of typedef?

typedef declaration helps to make source code of a C program more readable. Its purpose is to redefine the name of an existing variable type. It provides a short and meaningful way to call a data type. typedef is useful when the name of the data type is long. Use of typedef can reduce length and complexity of data types.

 

 

 

 

 

 

 

 

 

 

 

Differences among concepts

What is the difference between 'break' and 'continue' statements?

Differences between 'break' and 'continue' statements:

break

continue

1. break is a keyword used to terminate the loop or exit from the block.The control jumps to next statement after the loop or block.

1. continue is a keyword used for skipping the current iteration and go to next iteration of the loop

2.Syntax:

{

Statement 1;

Statement 2;

Statement n;

break;

}

2.Syntax:

{

Statement 1;

continue;

Statement 2;

}

3. break can be used with for, while, do- while, and switch statements.When break is used in nested loops i.e. within the inner most loop then only the innermost loop is terminated.

3. This statement when occurs in a loop does not terminate it but skips the statements after this continue statement. The control goes to the next iteration. continue can be used with for, while and do-while.

4. Example:

i = 1, j = 0;

while(i<=5){

 

i=i+1;

if(i== 2)

 

break;

j=j+1;

 

}

4. Example:

i = 1, j = 0;

while(i<=5){

 

i=i+1;

if(i== 2)

 

continue;

j=j+1;

 

Is it better to use malloc() or calloc()?

Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory at least big enough to hold them all:
void *calloc( size_t numElements, size_t sizeOfElement );
There's one major difference and one minor difference between the two functions. The major difference is that malloc() doesn't initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you're going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you're going to use as a pointer is set to all zero bits. That's usually a null pointer, but it's not guaranteed.Anything you're going to use as a float or double is set to all zero bits; that's a floating-point zero on some types of machines, but not on all.
The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.

 

What is the difference between a string and an array?

An array is an array of anything. A string is a specific kind of an array with a well-known convention to determine its length.
There are two kinds of programming languages: those in which a string is just an array of characters, and those in which it's a special type. In C, a string is just an array of characters (type char), with one wrinkle: a C string always ends with a NUL character. The "value" of an array is the same as the address of (or a pointer to) the first element; so, frequently, a C string and a pointer to char are used to mean the same thing.
An array can be any length. If it's passed to a function, there's no way the function can tell how long the array is supposed to be, unless some convention is used. The convention for strings is NUL termination; the last character is an ASCII NUL ('') character.


What are the differences between structures and unions?

Structures and Unions are used to store members of different data types.

STRUCTURE

UNION

a)Declaration:

struct

  {

   data type member1;

   data type member2;

  };

a)Declaration:

union

  {

   data type member1;

   data type member2;

  };

b)Every structure member is allocated memory when a structure variable is defined.
Example:

struct emp {

 char name[5];

 

 int age;

 float sal;

 

};

 

 

struct emp e1;

Memory allocated for structure is 5+4+4=13 bytes(assuming sizeof int is 4, float is 4, char is 1). 5 byte for name, 4 bytes for age and 4 bytes for sal.

b)The memory equivalent to the largest item is allocated commonly for all members.
Example:

union emp1 {

 char name[5];

 

 int age;

 float sal;

 

};

 

 

union emp1 e2;

Memory allocated to a union is equal to size of the largest member. In this case, char name[5] is the largest-sized member. Hence memory allocated to this union is 5 bytes.

c)All structure variables can be initialized at a time

struct st {

 int a;

 

 float b;

};

 

struct st s = { .a=4, .b=10.5 };

Structure is used when all members are to be independently used in a program.

c)Only one union member can be initialized at a time

union un {

 int a;

 

 float b;

};

 

 

union un un1 = { .a=10 };

Union is used when members of it are not required to be accessed at the same time.



=================================================================================================================

What is the difference between getchar and scanf functions for reading strings?

Differences between getchar and scanf functions for reading strings:

scanf

getchar

1. Entering of each character should be followed by return key.

1. Need not type return key.

2. Continuous stream of characters cannot be directly supplied using scanf function.

2. Continuous stream of characters can be directly supplied using getchar function

3. Scanf function can be used to provide data at execution time irrespective of its type(int, char, float).
Example:

#include<stdio.h>

int  main() {

 

char a[10];

printf("Enter a: \n");

 

scanf("%s",a);

return 0;

 

}

3. getchar() function is used only with character type.
Example:

#include<stdio.h>

int main() {

 

char a;

printf("Enter any character: \n");

 

a = getchar();

printf("Character entered:%c \n",a);

 

return 0;

}

4. scanf() returns the number of items read successfully. A return value 0 indicates that no fields were read. EOF(end of file) is returned in case of an error or if end-of-file/end-of-string character is encountered.

4. getchar() returns the character entered as the value of the function. It returns EOF in case of an error. It is recommeded to use getchar instead of scanf.

 



Questions on Pointers

What is a pointer?

A pointer is a special variable in C language meant just to store address of any other variable or function. Pointer variables unlike ordinary variables cannot be operated with all the arithmetic operations such as '*','%' operators.

Are pointers integers?

No, pointers are not integers.A pointer is an address.It is merely a positive number and not an integer.

 

 

How are pointer variables initialized?

Pointer variable are initialized by one of the following two ways
- Static memory allocation
- Dynamic memory allocation

What does it mean when a pointer is used in an if statement?

Any time a pointer is used as a condition, it means "Is this a non-null pointer?" A pointer can be used in an if, while, for, or do/while statement, or in a conditional expression.

What is indirection?

If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any other object in memory, you have an indirect reference to its value.

In C, why is the void pointer useful?

When would you use it? The void pointer is useful becuase it is a generic pointer that any pointer can be cast into and back again without loss of information.

 


Questions on Variables and Arrays

 

What is the difference between declaring a variable and defining a variable?

Declaring a variable means describing its type to the compiler but not allocating any space for it. Defining a variable means declaring it and also allocating space to hold the variable. You can also initialize a variable at the time it is defined.

 

In C, what is the difference between a static variable and global variable?

A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files).

  What is difference between for loop and while loop and do-while loop in C language?

for loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of an iterative loop, it is recommended to use 'for' loop.

Syntax:

for(initialisation;condition;increment/decrement)
{
//block of statements
increment or decrement
}

 

 

 

while loop: When it is not necessary to do initialization, condition check and increment/decrement in a single statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is present.

Syntax:

While(cond)

{

Block of statements

}

do-while loop: in this kind of looping first time statements in the block gets executed and then checks for the condition, if condition becomes true then it executes the loop or comes out of the loop.

Syntax :

Do{

Block of statements

}while(comdition)

 

What are the characteristics of arrays in C?

1) An array holds elements that have the same data type.

2) Array elements are stored in subsequent memory locations

3) Two-dimensional array elements are stored row by row in subsequent memory locations.

4) Array name represents the address of the starting element

5) Array size should be mentioned in the declaration. Array size must be a constant expression and not a variable.

6)While declaring the 2D array, the number of columns should be specified and its a mandatory. where as for number of rows there is no such rule.

7)An Array index by default starts from 0 and ends with the index no. (n-1).
8)The size of an Array can not be changed at Run Time