C Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

How do you write your own sizeof operator?

#define my_sizeof(type) (char *)(&type+1)-(char*)(&type)

include file with std input/output

#include <stdio.h>

Struct

'struct' keyword is used to create a structure. Following is an example. struct address { char name[50]; char street[100]; char city[50]; char state[20]; int pin; };

What is the meaning of base address of the array?

The started address of the array is called the base address of the array

Which keyword is used to perform unconditional branching

goto

Which builit-in library function can be used to resize the allocated dynamic memory?

realloc()

What are the operators under the category of ternary operators?

(? :)

When should we use pointers in a C program?

- To get address of variable - For achieving pass by reference in C: Pointers allow different functions to share and modify their local variables - To pass large structures so that complete copy of the structure can be avoided - To implement "linked" data structures like linked lists and binary trees

What is the purpose of the keyword typedef?

-It is used to alias the exisiting type -Also used to simplify the complex declaration of the type

What is the default value of local and global variables?

-Local variables default to garbage values -global variables default to a value of 0

What are local static variables? What is their use?

A local static variable is a variable whose lifetime doesn't end with a function call hwere it is declared. It extends for the lifetime of complete program. All calls to the function share the same copy of local static variables. Static variables can be used to count the number of times a function is called. Also, static variables get the default value as 0. For example, the folloing program prints "0 1" #include <stdio.h> void fun(){ static int x; printf("%d ", x); x = x + 1; } int main() { fun(); fun(); return 0; }

What is a pointer to a function? Give the general syntax for the same.

A pointer holding the reference of the function is called point to a function. T(*fun_ptr) (T1, T2) // Where T is any data type Once fun_ptr refers a function the same can be invoked using the pointer as follows fun_ptr(); or (*fun_ptr)();

What is a token?

A program consists of various tokens and a token is either a keyword an identifier, a constant, a string literal, or a symbol.

What is a nested structure??

A structure containing an element of another structure as its member is referred so

What is a self-referential structure?

A structure containing the same structure pointer variable as its element is called as self-referential structure.

Distinguish between malloc() and calloc() memory allocation

Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0's.

What are the valid places for the keyword break to appear?

Break can appear only with in the loop control and switch statement. The purpose of the break is to bring the control out from the said blocks.

What is keyword auto for?

By default every local variable of the function automatic (auto). In the below function both the variables 'i' and 'j' are automatic variables void f(){ int i; auto int j; } NOTE - A global variable can't be an automatic variable

What are main characteristics of C language?

C is a procedural language. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style. These features make it suitable for system programming like operating system or compiler development.

What is Dangling pointer?

Dangling Pointer is a pointer that doesn't point to a valid memory location. Dangling pointers arize when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer points to the memory location of the deallocated memory. ALWAYS make a pointer NULL when memory pointed by it is deallocated in the middle of a program to avoid a dangling pointer. int *ptr = (int *)malloc(sizeof(int)); free(ptr); // ptr is dantling pointer now and operations like following are invalid *ptr = 10; // OR int *ptr = NULL { int x = 10; ptr = &x; } // x goes out of scope and memory allocated to x is free now. So ptr is dangling pointer now.

difference between declaration and definition of a variable/function

Declaration of a variable/function declares that the var func exists somewhere in the program but memory is not allocated. In the case of var, thi sindicates type of var. Ic case of function, this indicates, argument types, number, order, and function return type. With fun/var definition, memory is allocated for the fun/var. Thus, variable can be declared many times, but only defined once.

Explain modular programming

Dividing the program in to sub programs (modules/function) to achieve the given task a modular approach. More generic functions defintion gives the ability to reuse the function, such as built-in library functions.

What are enumerations?

Enumerations are lists of integer constants with a name. Enumerations are defined with keyword enum

What is the remainder for 5.0 % 2

Error, it is invalid that either of the operands for the modulus operator is a real number

Where is an automatic variable stored?

Every local variable by default being an auto variable is stored in stack memory

How is a negative integer stored?

Get the two's compliment of the same positive integer eg 1011 (-5) step-1 Ones compliment of 5: 1010 step-2 Add 1 to above giving 1011, which is -5

What is a static variable?

If a global variable is static then its visibility is limited to the same source code

What is the difference between including the header file within angular braces <> and double quotes.

If a header file is include within <> then the compiler searches for the particular header file only with in the built include path. If a header file is included in "", then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path.

When should we use the register storage specifier?

If a variable is used most frequently then it should be declared using register storage specifier, the possibly the compiler gives CPU register for its storage to speed up the look up of the variable.

When to use -> (arrow) operator

If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is used.

How is free keyword different from delete.

In C++, delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

What are static functions? What is their use?

In C, functions are global by default. The "static" keyword before a function name makes it static. Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.

Interrupts

Interrupts is a mechanism by which an I/O or an instruction can suspend the normal execution of processor and gets itself serviced like it has higher priority. For example a processor doing a normal execution can be interrupted by some sensor to execute a particular process that is present in ISR (Interrupt Service Routine). After executing the ISR processor can again resume the normal execution.

Where the address operator (&) cannot be used?

It cannot be used on constants It cannot be used on variables which are declared using register storage class.

What is a pointer on pointer?

It's a pointer variable which can hold the address of another pointer variable. int x = 5, *p=&x, **q=&p; Therefore 'x' can be accessed by **q.

What is memory leak? Why should it be avoided?

Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particulary serious issues for porgrams like daemons and servers which by difinition never terminate. // Function with memory leak #include <stdlib.h> void f() { int *ptr = (int *) malloc(sizeof(int)); // Do some work return; // return without freeing ptr* }

What is NULL pointer?

NULL is used to indicate that the pointer doesn't point to a valid location. Ideally, we should initialize pointers as NULL if we don't know their value at the time of declaration. ALWAYS make a pointer NULL when memory pointed by it is deallocated in the middle of a program, otherwise, you end up with a dangling pointer

Does a built-in header file contain built-in function definition?

No, the header file only declares functions. The definition is in library which is linked by the linker.

What is the difference between array and pointer?

Pointers are used for storing address of dynamically allocated arrays and for arrays which are passed as arguments to functions. In other contexts, arrays and pointers are two different things. int main() { int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr = arr; printf("Size of arr[] %d\n", sizeof(arr)); printf("Size of ptr %d", sizeof(ptr)); return 0; ) Output: Size of arr[] 24 Size of ptr = 4

What is a preprocessor?

Preprocessor is a directive to the compiler to perform certain things before the actual compilation process begins

S++ or S = S + 1, which can be recommended to increment the value by 1 and why?

S++ bc S++ is a single machine instruction (INC) internally

What is scope of a variable?

Scope of a variable is the part of the program where the variable may directly be accessible. In C, all identifiers are lexically (or statically) scoped.

What are command line arguments?

The arguments which we pass to the main () function while executing the program are called as command line arguments. First Argument of main represnts the count of arguments (below in count) and updated automatically by operating system. Second argument holds the command line arguments--parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. main (int count, char *args[])

What is the difference between actual and formal parameters?

The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters

What is volatile keyword?

The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.

What is the use of the extern storage specifier?

Used to resolve the scope of global symbol. main(){ extern int i; printf("%d ", i); } int i = 20;

What are bit fields

We can create integer structure members of differing size apart from non-standard size using bit fields. Such structure size is automatically adjusted with the multiple of integer size of the machine

What is the advantage of declaring void pointers?

We can use these as a tool of abstraction / modularity. We use these when we do not know what type of the memory address the pointer variable is going to hold. Generic functions. Malloc and Calloc return void pointers bc don't know what type they are going to allocate memory for. Void pointers cannot be dereferenced.

Can we assign a float variable to a long integer variable?

Yes, with loss of fractional part.

What are different storage class specifiers in C?

auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope) register: This storage class declares register variables that have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available static: Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist until the termination of the program. Thus, no new memory is allocated because they are not re-declared. extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere.

What are the different ways of passing parameters to the functions? Which to use and when?

call by value - we send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used. call by reference = We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters.

compile to make executable file

clang program.c -o program

Explain the syntax for for loop

for(expression-1; expression-2;expression-3){ // stuff } When control reaches for expression-1 is executed first. Then following expression 2, and if expression-2 evaluates to non-zero "set of statements" and expression-3 is executed, follows expression-2

What is the difference between i++ and ++i?

i++ increments i and returns old value of i ++i increments i and returns new value of i generally, safer to go with ++i

main function

int main(int argc, const char* argv[]) { }

How will you print "Hello World" without semicolon?

int main(void) { if (printf("Hello World")) ; }

declare array of arrays v declare array

int nums[10] v int nums[10][20]

Can a program be compiled without main() function?

it can be compiled but it cannot be executed without a main() function

What is I-Value?

l-Value or location value refers to an expression that can be used on left side of assignment operator. For example in expression "a = 3", a is l-value and 3 is r-value. l-Values are of two types: "nonmodifiable l-value" represents a I-value that can not be modified, const variables are "nonmodifiable l-value" "modifiable l-value" represents a I-value that can be modified.

What is the purpose of the function sprintf()

prints the formatted output onto the character array

Toggle only second bit of a 8 bit char(both from right and left). Write one line code

pt = pt & ~(1 << i);

How will you print numbers from 1 to 100 without using a loop?

void printNos(unsigned int n) { if (n > 0) { printNos(n-1); printf("%d ", n); } }

Can a variable be both const and volatile?

yes, the const means that the variable cannot be assigned a new value. The value can be changed by other code or pointer. For example the following program works fine int main(void) { const volatile int local = 10; int *ptr = (int*) &local; printf("Initial value of local : %d \n", local)); *ptr = 100; printf("Modified value of local: %d \n", local)); return 0; )


Ensembles d'études connexes

Algebra 2B: Review of quadratic Functions and Equations

View Set

Biology - Exam 1 questions and answers

View Set

GEN BUS 310 - Modules 1-4 PRACTICE EXAMS

View Set

ACG 2071 Ch 4 Study Guide Questions

View Set

Practice identifying solutions to linear equations

View Set

4th President: James Madison(1809-1817)

View Set

Investment Companies: REITs/BDCs

View Set

Reproduction at the Cellular Level, The Cellular Basis or Inheritance, Patterns of Inheritance

View Set

Organs that belong to more than one system

View Set