Posts

Showing posts with the label c interview questions

what are static variables and globals

In c programming static variable is a special type of variable can retain its value between invocations .It has two types : 1. Static to function or control block 2. Static to the file If it is static to function it will retain the value when the function is called again and again . Eg Void foo() { Static int a; a++; printf(“%d\n”,a); } In consecutive calls it will have values 1 , 2 ….. But cant be accessed outside of the function. In the static to the file scenario the variable is commonly declared at the top like the globals . it is accessible to all functions but it will retain the value. Difference between the globals , when static is in a header file it will have 1 copy per file that include the header. Eg: -----------------test.h----------------- static int var; ----------------- mainfile.c ---------------------- #include #include ”test.h” Int main (){ printf("var in %s: %d\n ", __FILE__, ++var); in_file2(); } ----------...

volatile variables ? example

In embedded we deal with special features in c language that are provided to make building systems convenient. One such feature is volatile variable : A variable should be declared volatile whenever its value could change unexpectedly viz by external influences like the variable representing memory mapped peripheral register. Example: static int var; void test(void) { var = 0; while (var != 255) continue; } The above code sets the value in var to 0. It then starts to poll that value in a loop until the value of var becomes 255. An optimizing compiler will notice that no other code can possibly change the value stored in 'var', and therefore assume that it will remain equal to 0 at all times. The compiler will then replace the function body with an infinite loop, similar to this: void test_opt(void) { var = 0; while (TRUE) continue; } solution is : volatile int var;