C Language FAQs - Part 1



01. How C program works?

Ans:
#include<stdio.h>
#define x 1      // 
http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html
main()
{
int i;
i = 0;
i = i + x;
printf("The value of i is %d \n", i);
Printf("Hello");                          // Run time error (Linking error), Think
}
Before compilation, preprocessor comes into picture, and the value of X gets replaced by 1 before actual compilation starts.
Then compiler looks for main() and starts compiling, and checks for the syntax format.
Then when we run the program the linking comes into picture, compiler links the functions and all called within the file, are really exists in the library or not?
If everything is Okay then program runs successfully...
Manythigs I have skipped (Where variable gets stored and all) and I briefed  some overall idea.

Refer 
http://www.howstuffworks.com/c.htm

02. What is the output of printf("%d")?

Ans:
main(){printf("%d");}
Output will be a Garbage.

03. Calloc vs Malloc

Ans:-
There are two differences.
First, is in the number of arguments. Malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments.
Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
·         calloc() allocates a memory area, the length will be the PRODUCT of its parameters. calloc fills the memory with ZERO's and returns a pointer to first byte. If it fails to locate enough space it returns a NULL pointer.


Syntax: ptr_var=(cast_type *)calloc(NO_OF_BLOCKS , SIZE_OF_EACH_BLOCK); 
i.e. ptr_var=(type *)calloc(n,s);

·         malloc() allocates a single block of memory of REQUSTED SIZE and returns a pointer to first byte. If it fails to locate requsted amount of memory it returns a NULL pointer.


Syntax: ptr_var=(cast_type *)malloc(SIZE_IN_BYTES);

04. Struct vs union

Think and Try
I just wanted to add make/add a point here, In Union:-
union u{
int x;
char y;
}
u.x = 0;
u.y = 1.;
printf("The value of u.x will be ? ") //Think before you scroll Down or look down
The o/p of x will be garbage.

05. #define vs #include

Try yourself

06. #define vs typedef; Explain


typedefs can correctly encode pointer types.where as #DEFINES are just replacements done by the preprocessor.
For example,
typedef char *String_t;
1.     #define String_d char *
2.     String_t s1, s2; String_d s3, s4;
s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention.

07. #define vs enum; Which one is better? And Why?

Ans: Click the below link for better understnding
Coming to the question:- Which one is better and why?
It depends on the programmer.
If there is only few changes needed then #define is the best solution.
But if there are lots of changes need to be done then the solution is enum.
e.g,
#define x 1 // if tomorrow you are changing the value of x from 1 to 2 then #define is effective
similarly if there are many #defines like
#define X1 1
#define X2 2
.
.
.
#define Xn n
In this case we can use enum, to reduce the complexity.
enum {X1, X2....Xn};
Now the question is if X10 value changed from 10 to 50 but the rest of the sequence are unchanged then how to tackle? Think !!!

08.Compilation How to reduce a final size of executable?


Ans:
Size of the final execuatable can be reduced using dynamic linking for libraries.

09. What does static variable and function mean?

void func() {
        static int x = 0; // x is initialized only once across three calls of func()
        printf("%d, ", x); // outputs the value of x
        x = x + 1;
fun();
}
 O/p:- 0,1,2,3,.....
Because the scope of static variable is always to that particular function/file(incase of Global declaration).
It gets stored in Data Segment
The default value of static variable is always Zero, It (Default value or user-defined value) gets initialized at the run time.And it get initialized only once.
In this above example the value of x is initialized to Zero.
When next time fun() call happens, the variable x does not get initialized again.
Static Function:-
in file 1.c                    In file 2.c
main()                         static void fun(); void fun1();
{ fun(); fun1();}              void fun{ printf("It is a static fun") ;}
    void fun1{printf("It is not a static fun");}
Try to compile and see what happens, That (The warning or error) is your answer.
/*undefined reference to `Func' */ //Ans:: the fun() is local to file 2.c and can't get accessed by main().
*****
Local Variables are stored in Stack.
Register variables are stored in Register.
Global & static variables are stored in data segment.
The memory created dynamically are stored in Heap
And the C program instructions get stored in code segment
and the extern variables also stored in data segment.
*****

10. Can a static variable accessed from outside of the file?

Ans: See Qestion number 9.

11. Macro vs inline; Explain each of them; and which one is better why?

12. What are different storage classes? Why register is used?

13. Const vs static vs #define

14. What is the difference between strings and character arrays?

15. Difference between const char* p and char const* p

16. **p vs &*p vs *&p

17. What is hashing?

18. memmove vs memcpy vs memset

19. How free() works?

20. Can a variable be both const and volatile? Explain Volatile

21. Can include files be nested?

22. What is NULL pointer? Why it is required?

23. Is NULL = = 0?

24. What is static memory allocation and dynamic memory allocation?

25. How you do dynamic memory allocation?

26. Is realloc() uses the same memory location which was used by malloc()?

27. Describe different types of pointers?

28. How are pointer variables initialized?

29. Difference between arrays and pointers?

30. Is using exit() the same as using return?

31. declaring a variable vs defining a variable

32. lvalue vs rvalue

33. Differentiate between an internal static and external static variable?

34. string vs array?

35. Call by value vs call by reference

36. What are advantages and disadvantages of external storage class?

37. Describe void pointer

38. Typecast when to use and when not to use?

39. Switch vs if; which one is better? Why?

40. Linker vs linkage?

41. Function vs built-in function

42. Why should I prototype a function?

43. Array vs Linked list

44. Write a code for String reverse, strlen, etc

45. Explain C memory

46. Little endian vs big endian? Why it is required? Which one is better? How the conversion happens? Write a pseudo code for hton() and ntoh()

47. How can you make sure that 3rd bit (Say 8-bits given to you) is set or not?

if ( number & (1<<n) ) – set – else – not set

48. How do you set/reset a particular bit?

#define SET_BIT(number,nth)  (number  |  1<<nth)
Set bit– number      = number  |  1<<n
Reset bit– number  = number  &  ~(1<<n)            (clear bit)
Toggle bit– number = number  ^  1<<n

49. Write the T-table of X-OR

Same bits – 0 ; diff bits - 1

50. What is code optimization?

51. How code optimization does not happen when it comes to VOLATILE? Explain

1.     When we use the word Optimise, we mean that the variable in the memory can be changed only by the compiler whenever the code is executed. Volatile modifiers cannot be optimised by the compiler, During linking process the code is allocated physical memory in the internal memory. so during the link process( generation of .lnk file during compilation) these variables are placed in the heap instead of main memory. Compiler cannot modify the variable until unless a copy is copied to RAM for execution. So the compiler allocates a different memory location for the variable. These are called un-optimized location. the variables in this location are not dependent on the compiler to change the value. instead interrupt, ports, serial, hardware are given permission to access these variables whenever they raise a request.
When a memory is optimized, then the life of that variable is limited only till the function executes then it is destroyed, but volatile are not destroyed, but keep value in it till there is any change done by external entities. Whenever these variables are accessed only the last updated value is seen in the register.

Uploading a example after this. the best example is RTC(Real Time Clock). in the PC. even when the PC is shut down , and later restarted, the clock updates the latest current time.

e.g.:
volatile char time;
void update(void)
{
time =time+1;
}

void main()
{
time=0;
while(time<100);
}


without volatile modifier the compiler looks at this as 2 different statements.
1. time =0;
2. while(time<100);

since time =0; 0<100, so the loop always stay in the same line till the condition is true.
Time never reach 100. So when memory is optimized then it can be changed only through execution of explicit statement which modifies the value. in the above case it does not change.

If we use volatile modifier, this disables optimization, forcing the program to fetch a new value from the variable every time variable is accessed.

Hope this answers your question. if not then I can still continue my explanation in my next post. Let me know if you got anything from this.

Always remember you cannot simulate the condition of volatile in c51 or any compiler as Heap memory cannot be simulated in keil. It can be seen only on hardware.

52. Const to Pointer vs Pointer to Const

53. Difference between Static and Dynamic Library

54. Write a function which takes few arguments and displays the arguments

e.g fun(int arg1, int arg2, int arg3); // May be infinite numbers of arguments
o/p will be value of agr1, arg2, arg3....
Ans:
Use logic of printf()

55. How to write and read data from an address location in C language?

Ans:
Method -1 Assume it's 8 bits:

char * address = (char *)3000; // address is a pointer to address 3000
char val;

*address = 36; // write 36 to 8 bit location at address

val = *address; // read 8 bit value from address
Method - 2
char *ptr; //u can take any datatype
ptr = 0x0000000a; //"0x0000000a" is hexadecimal adrr. bit

*ptr = 'a'; //here u put data "i had put a"

same as u can read it by

char d,*ptr;
'"
" // as it is above
'"
d = *ptr; // u`r value read from ptr is store in d

http://in.answers.yahoo.com/question/index?qid=20091118002501AAYTcjU

56. What is segmentation fault?

57. volatile vs const volatile, Explain.

58. How function call happens in C? or How function/function call works internally?


No comments:

Post a Comment