Embedded C Programming Interview Questions And Answers

  1. Embedded Programming Interview Questions
  2. C Programming Interview Questions
  3. Embedded Interview Questions

Introduction to C Programming Interview Questions. Preparing for a job interview in C Programming. I am sure you want to know the most common 2020 C Programming interview questions and answers that will help you crack the C Programming interview with ease. Below is the list of top C Programming interview questions and answers at your rescue. C Pointers Tricky Questions and Answers. In most of the MNC interview questions such as in ZOHO interview question, IVTL Infoview interview questions, Amazon interview questions, GOOGLE interview questions, Infosys interview questions and even in Voonik interview questions, We come across several Tricky C Questions about which 2:5 of the questions are from pointers in c. Solving that kind of. 10 Microcontroller interview questions and answers. This page describes Microcontroller questionnaire written by specialists in Microcontroller embedded domain. This top 10 Microcontroller interview questions and answers will help interviewee pass the job interview for Microcontroller Handware or programming job position with ease.

  • C Programming Tutorial
  • C Programming useful Resources
  • Selected Reading

Dear readers, these C Programming Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C Programming. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −

  • What is a pointer on pointer?

      It’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable.

      Therefore ‘x’ can be accessed by **q.

  • Distinguish between malloc() & calloc() memory allocation.

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

  • What is keyword auto for?

      By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables.

      NOTE − A global variable can’t be an automatic variable.

  • What are the valid places for the keyword break to appear.

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

  • Explain the syntax for for loop.

      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 difference between including the header file with-in angular braces < > and double quotes “ “

      If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with 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.

  • How a negative integer is stored.

      Get the two’s compliment of the same positive integer. Eg: 1011 (-5)

      Step-1 − One’s compliment of 5 : 1010

      Step-2 − Add 1 to above, giving 1011, which is -5

  • What is a static variable?

      A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice.

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

  • What is a NULL pointer?

      A pointer pointing to nothing is called so. Eg: char *p=NULL;

  • What is the purpose of extern storage specifier?

      Used to resolve the scope of global symbol.

  • Explain the purpose of the function sprintf().

      Prints the formatted output onto the character array.

  • What is the meaning of base address of the array?

      The starting address of the array is called as the base address of the array.

  • When should we use the register storage specifier?

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

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

      S++, as it is single machine instruction (INC) internally.

  • What is a dangling pointer?

      A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer.

  • What is the purpose of the keyword typedef?

      It is used to alias the existing type. Also used to simplify the complex declaration of the type.

  • What is lvalue and rvalue?

      The expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a constant.

  • 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.

  • Can a program be compiled without main() function?

      Yes, it can be but cannot be executed, as the execution requires main() function definition.

  • What is the advantage of declaring void pointers?

      When we do not know what type of the memory address the pointer variable is going to hold, then we declare a void pointer for such.

  • Where an automatic variable is stored?

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

  • What is a nested structure?

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

  • What is the difference between variable declaration and variable definition?

      Declaration associates type to the variable whereas definition gives the value to the variable.

  • What is a self-referential structure?

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

  • Does a built-in header file contains built-in function definition?

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

  • Explain modular programming.

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

  • What is a token?

      A C 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 preprocessor?

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

  • Explain the use of %i format specifier w.r.t scanf().

      Can be used to input integer in all the supported format.

  • How can you print a (backslash) using any of the printf() family of functions.

      Escape it using (backslash).

  • Does a break is required by default case in switch statement?

      Yes, if it is not appearing as the last case and if we do not want the control to flow to the following case after default if any.

  • When to user -> (arrow) operator.

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

  • 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 are command line arguments?

      The arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system.

  • What are the different ways of passing parameters to the functions? Which to use 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.

  • What is the purpose of built-in stricmp() function.

      It compares two strings by ignoring the case.

  • Describe the file opening mode “w+”.

      Opens a file both for reading and writing. If a file is not existing it creates one, else if the file is existing it will be over written.

  • Where the address of operator (&) cannot be used?

      It cannot be used on constants.

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

  • Is FILE a built-in data type?
      No, it is a structure defined in stdio.h.
  • What is reminder for 5.0 % 2?

      Error, It is invalid that either of the operands for the modulus operator (%) is a real number.

  • How many operators are there under the category of ternary operators?

      There is only one operator and is conditional operator (? : ).

  • Which key word is used to perform unconditional branching?

      goto

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

      A pointer holding the reference of the function is called pointer to a function. In general it is declared as follows.

      Once fun_ptr refers a function the same can be invoked using the pointer as follows.

  • Explain the use of comma operator (,).

      Comma operator can be used to separate two or more expressions.

  • What is a NULL statement?

      A null statement is no executable statements such as ; (semicolon).

      Above does nothing 10 times.

  • What is a static function?

      A function’s definition prefixed with static keyword is called as a static function. You would make a function static if it should be called only within the same source code.

  • Which compiler switch to be used for compiling the programs using math library with gcc compiler?

      Opiton –lm to be used as > gcc –lm <file.c>

  • Which operator is used to continue the definition of macro in the next line?

      Backward slash () is used.

  • Which operator is used to receive the variable number of arguments for a function?

      Ellipses (…) is used for the same. A general function definition looks as follows

  • What is the problem with the following coding snippet?

      s1 points to a string constant and cannot be altered.

  • Which built-in library function can be used to re-size the allocated dynamic memory?

      realloc().

  • Define an array.

      Array is collection of similar data items under a common name.

  • What are enumerations?

      Enumerations are list of integer constants with name. Enumerators are defined with the keyword enum.

  • Which built-in function can be used to move the file pointer internally?

      fseek()

  • What is a variable?

      A variable is the name storage.

  • Who designed C programming language?

      Dennis M Ritchie.

  • C is successor of which programming language?

      B

  • What is the full form of ANSI?

      American National Standards Institute.

  • Which operator can be used to determine the size of a data type or variable?

      sizeof

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

      Yes, with loss of fractional part.

  • Is 068 a valid octal number?

      No, it contains invalid octal digits.

  • What it the return value of a relational operator if it returns any?

      Return a value 1 if the relation between the expressions is true, else 0.

  • How does bitwise operator XOR works.

      If both the corresponding bits are same it gives 0 else 1.

  • What is an infinite loop?

      A loop executing repeatedly as the loop-expression always evaluates to true such as

  • Can variables belonging to different scope have same name? If so show an example.

      Variables belonging to different scope can have same name as in the following code snippet.

  • What is the default value of local and global variables?

      Local variables get garbage value and global variables get a value 0 by default.

  • Can a pointer access the array?

      Pointer by holding array’s base address can access the array.

  • What are valid operations on pointers?

      The only two permitted operations on pointers are

      • Comparision ii) Addition/Substraction (excluding void pointers)
  • What is a string length?

      It is the count of character excluding the ‘0’ character.

  • What is the built-in function to append one string to another?

      strcat() form the header string.h

  • Which operator can be used to access union elements if union variable is a pointer variable?

      Arrow (->) operator.

  • Explain about ‘stdin’.

      stdin in a pointer variable which is by default opened for standard input device.

  • Name a function which can be used to close the file stream.

      fclose().

  • What is the purpose of #undef preprocessor?

      It be used to undefine an existing macro definition.

  • Define a structure.

      A structure can be defined of collection of heterogeneous data items.

  • Name the predefined macro which be used to determine whether your compiler is ANSI standard or not?

      __STDC__

  • What is typecasting?

      Typecasting is a way to convert a variable/constant from one type to another type.

  • What is recursion?

      Function calling itself is called as recursion.

  • Which function can be used to release the dynamic allocated memory?

      free().

  • What is the first string in the argument vector w.r.t command line arguments?

      Program name.

  • How can we determine whether a file is successfully opened or not using fopen() function?

      On failure fopen() returns NULL, otherwise opened successfully.

  • What is the output file generated by the linker.

      Linker generates the executable file.

  • What is the maximum length of an identifier?

      Ideally it is 32 characters and also implementation dependent.

  • What is the default function call method?

      By default the functions are called by value.

  • Functions must and should be declared. Comment on this.

      Function declaration is optional if the same is invoked after its definition.

  • When the macros gets expanded?

      At the time of preprocessing.

  • Can a function return multiple values to the caller using return reserved word?

      No, only one value can be returned to the caller.

  • What is a constant pointer?

      A pointer which is not allowed to be altered to hold another address after it is holding one.

  • To make pointer generic for which date type it need to be declared?

      Void

  • Can the structure variable be initialized as soon as it is declared?

      Yes, w.r.t the order of structure elements only.

  • Is there a way to compare two structure variables?

      There is no such. We need to compare element by element of the structure variables.

  • Which built-in library function can be used to match a patter from the string?

      Strstr()

  • What is difference between far and near pointers?

      In first place they are non-standard keywords. A near pointer can access only 2^15 memory space and far pointer can access 2^32 memory space. Both the keywords are implementation specific and are non-standard.

  • Can we nest comments in a C code?

      No, we cannot.

  • Which control loop is recommended if you have to execute set of statements for fixed number of times?

      for – Loop.

  • What is a constant?

      A value which cannot be modified is called so. Such variables are qualified with the keyword const.

  • Can we use just the tag name of structures to declare the variables for the same?

      No, we need to use both the keyword ‘struct’ and the tag name.

  • Can the main() function left empty?

      Yes, possibly the program doing nothing.

  • Can one function call another?

      Yes, any user defined function can call any function.

  • Apart from Dennis Ritchie who the other person who contributed in design of C language.

      Brain Kernighan

What is Next ?

Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong.

Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)

cprogramming_questions_answers.htm

An obligatory and significant part of the recruitment process for embedded systems programmers seems to be the ‘C Test’. Over the years, I have had to both take and prepare such tests and in doing so have realized that these tests can be very informative for both the interviewer and interviewee. Furthermore, when given outside the pressure of an interview situation, they can also be quite entertaining (hence this article).

From the interviewee’s perspective, you can learn a lot about the person that has written or administered the test. Is the test designed to show off the writer’s knowledge of the minutiae of the ANSI standard rather than to test practical know-how? Does it test ludicrous knowledge, such as the ASCII values of certain characters? Are the questions heavily slanted towards your knowledge of system calls and memory allocation strategies, indicating that the writer may spend his time programming computers instead of embedded systems? If any of these are true, then I know I would seriously doubt whether I want the job in question.

From the interviewer’s perspective, a test can reveal several things about the candidate. Primarily, one can determine the level of the candidate’s knowledge of C. However, it is also very interesting to see how the person responds to questions to which they do not know the answers. Do they make intelligent choices, backed up with some good intuition, or do they just guess? Are they defensive when they are stumped, or do they exhibit a real curiosity about the problem, and see it as an opportunity to learn something? I find this information as useful as their raw performance on the test.

With these ideas in mind, I have attempted to construct a test that is heavily slanted towards the requirements of embedded systems. This is a lousy test to give to someone seeking a job writing compilers! The questions are almost all drawn from situations I have encountered over the years. Some of them are very tough; however, they should all be informative.

This test may be given to a wide range of candidates. Most entry-level applicants will do poorly on this test, while seasoned veterans should do very well. Points are not assigned to each question, as this tends to arbitrarily weight certain questions. However, if you choose to adapt this test for your own uses, feel free to assign scores.

Preprocessor

1. Using the #define statement, how would you declare a manifest constant that returns the number of seconds in a year? Disregard leap years in your answer.

#define SECONDS_PER_YEAR (60UL * 60UL * 24UL * 365UL)

I’m looking for several things here:

(a) Basic knowledge of the #define syntax (i.e. no semi-colon at the end, the need to parenthesize etc.).

(b) A good choice of name, with capitalization and underscores.

(c) An understanding that the pre-processor will evaluate constant expressions for you. Thus, it is clearer, and penalty free to spell out how you are calculating the number of seconds in a year, rather than actually doing the calculation yourself.

(d) A realization that the expression will overflow an integer argument on a 16 bit machine – hence the need for the L, telling the compiler to treat the expression as a Long.

(e) As a bonus, if you modified the expression with a UL (indicating unsigned long), then you are off to a great start because you are showing that you are mindful of the perils of signed and unsigned types – and remember, first impressions count!

2. Write the ‘standard’ MIN macro. That is, a macro that takes two arguments and returns the smaller of the two arguments.

The purpose of this question is to test the following:

(a) Basic knowledge of the #define directive as used in macros. This is important, because until the inline operator becomes part of standard C, macros are the only portable way of generating inline code. Inline code is often necessary in embedded systems in order to achieve the required performance level.

(b) Knowledge of the ternary conditional operator. This exists in C because it allows the compiler to potentially produce more optimal code than an if-then-else sequence. Given that performance is normally an issue in embedded systems, knowledge and use of this construct is important.

(c) Understanding of the need to very carefully parenthesize arguments to macros.

(d) I also use this question to start a discussion on the side effects of macros, e.g. what happens when you write code such as :

least = MIN(*p++, b);

3. What is the purpose of the preprocessor directive #error?

Either you know the answer to this, or you don’t. If you don’t, then see reference 1. This question is very useful for differentiating between normal folks and the nerds. It’s only the nerds that actually read the appendices of C textbooks that find out about such things. Of course, if you aren’t looking for a nerd, the candidate better hope she doesn’t know the answer.

Infinite Loops

4. Infinite loops often arise in embedded systems. How does one code an infinite loop in C?

There are several solutions to this question. My preferred solution is:

while(1)

{

}

Another common construct is:

for(;;)

{

}

Personally, I dislike this construct because the syntax doesn’t exactly spell out what is going on. Thus, if a candidate gives this as a solution, I’ll use it as an opportunity to explore their rationale for doing so. If their answer is basically – ‘I was taught to do it this way and I have never thought about it since’ – then it tells me something (bad) about them. Conversely, if they state that it’s the K&R preferred method and the only way to get an infinite loop passed Lint, then they score bonus points.

A third solution is to use a goto:

Loop:

goto Loop;

Candidates that propose this are either assembly language programmers (which is probably good), or else they are closet BASIC / FORTRAN programmers looking to get into a new field.

Data declarations

5. Using the variable a, write down definitions for the following:

(a) An integer

(b) A pointer to an integer

(c) A pointer to a pointer to an integer

(d) An array of ten integers

(e) An array of ten pointers to integers

(f) A pointer to an array of ten integers

(g) A pointer to a function that takes an integer as an argument and returns an integer

(h) An array of ten pointers to functions that take an integer argument and return an integer.

The answers are:

(a) int a; // An integer

(b) int *a; // A pointer to an integer

(c) int **a; // A pointer to a pointer to an integer

(d) int a[10]; // An array of 10 integers

(e) int *a[10]; // An array of 10 pointers to integers

(f) int (*a)[10]; // A pointer to an array of 10 integers

Google embedded interview questions

(g) int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer

(h) int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer

People often claim that a couple of these are the sorts of thing that one looks up in textbooks – and I agree. While writing this article, I consulted textbooks to ensure the syntax was correct. However, I expect to be asked this question (or something close to it) when in an interview situation. Consequently, I make sure I know the answers – at least for the few hours of the interview. Candidates that don’t know the answers (or at least most of them) are simply unprepared for the interview. If they can’t be prepared for the interview, what will they be prepared for?

Static

6. What are the uses of the keyword static?

This simple question is rarely answered completely. Static has three distinct uses in C:

(a) A variable declared static within the body of a function maintains its value between function invocations.

Embedded Programming Interview Questions

(b) A variable declared static within a module [1], (but outside the body of a function) is accessible by all functions within that module. It is not accessible by functions within any other module. That is, it is a localized global.

(c) Functions declared static within a module may only be called by other functions within that module. That is, the scope of the function is localized to the module within which it is declared.

Most candidates get the first part correct. A reasonable number get the second part correct, while a pitiful number understand answer (c). This is a serious weakness in a candidate, since they obviously do not understand the importance and benefits of localizing the scope of both data and code.

Embedded C Programming Interview Questions And Answers

Const

7. What does the keyword const mean?

As soon as the interviewee says ‘const means constant’, I know I’m dealing with an amateur. Dan Saks has exhaustively covered const in the last year, such that every reader of ESP should be extremely familiar with what const can and cannot do for you. If you haven’t been reading that column, suffice it to say that const means “read-only”. Although this answer doesn’t really do the subject justice, I’d accept it as a correct answer. (If you want the detailed answer, then read Saks’ columns – carefully!).

If the candidate gets the answer correct, then I’ll ask him these supplemental questions:

What do the following incomplete [2] declarations mean?

const int a;

int const a;

const int *a;

int * const a;

int const * a const;

The first two mean the same thing, namely a is a const (read-only) integer. The third means a is a pointer to a const integer (i.e., the integer isn’t modifiable, but the pointer is). The fourth declares a to be a const pointer to an integer (i.e., the integer pointed to by a is modifiable, but the pointer is not). The final declaration declares a to be a const pointer to a const integer (i.e., neither the integer pointed to by a, nor the pointer itself may be modified).

If the candidate correctly answers these questions, I’ll be impressed.

Incidentally, one might wonder why I put so much emphasis on const, since it is very easy to write a correctly functioning program without ever using it. There are several reasons:

(a) The use of const conveys some very useful information to someone reading your code. In effect, declaring a parameter const tells the user about its intended usage. If you spend a lot of time cleaning up the mess left by other people, then you’ll quickly learn to appreciate this extra piece of information. (Of course, programmers that use const, rarely leave a mess for others to clean up…)

(b) const has the potential for generating tighter code by giving the optimizer some additional information.

(c) Code that uses const liberally is inherently protected by the compiler against inadvertent coding constructs that result in parameters being changed that should not be. In short, they tend to have fewer bugs.

Volatile

8. What does the keyword volatile mean? Give three different examples of its use.

A volatile variable is one that can change unexpectedly. Consequently, the compiler can make no assumptions about the value of the variable. In particular, the optimizer must be careful to reload the variable every time it is used instead of holding a copy in a register. Examples of volatile variables are:

(a) Hardware registers in peripherals (e.g., status registers)

(b) Non-stack variables referenced within an interrupt service routine.

(c) Variables shared by multiple tasks in a multi-threaded application.

If a candidate does not know the answer to this question, they aren’t hired. I consider this the most fundamental question that distinguishes between a ‘C programmer’ and an ‘embedded systems programmer’. Embedded folks deal with hardware, interrupts, RTOSes, and the like. All of these require volatile variables. Failure to understand the concept of volatile will lead to disaster.

On the (dubious) assumption that the interviewee gets this question correct, I like to probe a little deeper, to see if they really understand the full significance of volatile. In particular, I’ll ask them the following:

(a) Can a parameter be both const and volatile? Explain your answer.

(b) Can a pointer be volatile? Explain your answer.

(c) What is wrong with the following function?:

int square(volatile int *ptr)

{

}

Interview

The answers are as follows:

(a) Yes. An example is a read only status register. It is volatile because it can change unexpectedly. It is const because the program should not attempt to modify it.

(b) Yes. Although this is not very common. An example is when an interrupt service routine modifies a pointer to a buffer.

(c) This one is wicked. The intent of the code is to return the square of the value pointed to by *ptr. However, since *ptr points to a volatile parameter, the compiler will generate code that looks something like this:

int square(volatile int *ptr)

{

}

Since it is possible for the value of *ptr to change unexpectedly, it is possible for a and b to be different. Consequently, this code could return a number that is not a square! The correct way to code this is:

long square(volatile int *ptr)

{

}

Bit Manipulation

9. Embedded systems always require the user to manipulate bits in registers or variables. Given an integer variable a, write two code fragments. The first should set bit 3 of a. The second should clear bit 3 of a. In both cases, the remaining bits should be unmodified.

These are the three basic responses to this question:

(a) No idea. The interviewee cannot have done any embedded systems work.

(b) Use bit fields. Bit fields are right up there with trigraphs as the most brain-dead portion of C. Bit fields are inherently non-portable across compilers, and as such guarantee that your code is not reusable. I recently had the misfortune to look at a driver written by Infineon for one of their more complex communications chip. It used bit fields, and was completely useless because my compiler implemented the bit fields the other way around. The moral – never let a non-embedded person anywhere near a real piece of hardware! [3]

(c) Use #defines and bit masks. This is a highly portable method, and is the one that should be used. My optimal solution to this problem would be:

#define BIT3 (0x1 << 3)

static int a;

void set_bit3(void) {

}

void clear_bit3(void) {

a &= ~BIT3;

}

C Programming Interview Questions

Some people prefer to define a mask, together with manifest constants for the set & clear values. This is also acceptable. The important elements that I’m looking for are the use of manifest constants, together with the |= and &= ~ constructs.

Accessing fixed memory locations

10. Embedded systems are often characterized by requiring the programmer to access a specific memory location. On a certain project it is required to set an integer variable at the absolute address 0x67a9 to the value 0xaa55. The compiler is a pure ANSI compiler. Write code to accomplish this task.

This problem tests whether you know that it is legal to typecast an integer to a pointer in order to access an absolute location. The exact syntax varies depending upon one’s style. However, I would typically be looking for something like this:

A more obfuscated approach is:

*(int * const)(0x67a9) = 0xaa55;

Even if your taste runs more to the second solution, I suggest the first solution when you are in an interview situation.

Interrupts

11. Interrupts are an important part of embedded systems. Consequently, many compiler vendors offer an extension to standard C to support interrupts. Typically, this new key word is __interrupt. The following code uses __interrupt to define an interrupt service routine. Comment on the code.

__interrupt double compute_area(double radius) {

double area = PI * radius * radius;

printf(“nArea = %f”, area);

return area;

}

This function has so much wrong with it, it’s almost tough to know where to start.

(a) Interrupt service routines cannot return a value. If you don’t understand this, then you aren’t hired.

(b) ISR’s cannot be passed parameters. See item (a) for your employment prospects if you missed this.

(c) On many processors / compilers, floating point operations are not necessarily re-entrant. In some cases one needs to stack additional registers, in other cases, one simply cannot do floating point in an ISR. Furthermore, given that a general rule of thumb is that ISRs should be short and sweet, one wonders about the wisdom of doing floating point math here.

(d) In a similar vein to point (c), printf() often has problems with reentrancy and performance. If you missed points (c) & (d) then I wouldn’t be too hard on you. Needless to say, if you got these two points, then your employment prospects are looking better and better.

Code Examples

12. What does the following code output and why?

void foo(void)

{

unsigned int a = 6;

int b = -20;

(a+b > 6) ? puts(“> 6”) : puts(“<= 6”);

}

This question tests whether you understand the integer promotion rules in C – an area that I find is very poorly understood by many developers. Anyway, the answer is that this outputs “> 6”. The reason for this is that expressions involving signed and unsigned types have all operands promoted to unsigned types. Thus –20 becomes a very large positive integer and the expression evaluates to greater than 6. This is a very important point in embedded systems where unsigned data types should be used frequently (see reference 2). If you get this one wrong, then you are perilously close to not being hired.

13. Comment on the following code fragment?

unsigned int zero = 0;

unsigned int compzero = 0xFFFF; /*1’s complement of zero */

On machines where an int is not 16 bits, this will be incorrect. It should be coded:

This question really gets to whether the candidate understands the importance of word length on a computer. In my experience, good embedded programmers are critically aware of the underlying hardware and its limitations, whereas computer programmers tend to dismiss the hardware as a necessary annoyance.

By this stage, candidates are either completely demoralized – or they are on a roll and having a good time. If it is obvious that the candidate isn’t very good, then the test is terminated at this point. However, if the candidate is doing well, then I throw in these supplemental questions. These questions are hard, and I expect that only the very best candidates will do well on them. In posing these questions, I’m looking more at the way the candidate tackles the problems, rather than the answers. Anyway, have fun…

Dynamic Memory Allocation

14. Although not as common as in non-embedded computers, embedded systems still do dynamically allocate memory from the heap. What are the problems with dynamic memory allocation in embedded systems?

Here, I expect the user to mention memory fragmentation, problems with garbage collection, variable execution time, etc. This topic has been covered extensively in ESP, mainly by Plauger. His explanations are far more insightful than anything I could offer here, so go and read those back issues! Having lulled the candidate into a sense of false security, I then offer up this tidbit:

What does the following code fragment output and why?

char *ptr;

if ((ptr = (char *)malloc(0)) NULL) {

}

else {

puts(“Got a valid pointer”);

}

This is a fun question. I stumbled across this only recently, when a colleague of mine inadvertently passed a value of 0 to malloc, and got back a valid pointer! After doing some digging, I discovered that the result of malloc(0) is implementation defined, so that the correct answer is ‘it depends’. I use this to start a discussion on what the interviewee thinks is the correct thing for malloc to do. Getting the right answer here is nowhere near as important as the way you approach the problem and the rationale for your decision.

Typedef

15. Typedef is frequently used in C to declare synonyms for pre-existing data types. It is also possible to use the preprocessor to do something similar. For instance, consider the following code fragment:

The intent in both cases is to define dPS and tPS to be pointers to structure s. Which method (if any) is preferred and why?

This is a very subtle question, and anyone that gets it right (for the right reason) is to be congratulated or condemned (“get a life” springs to mind). The answer is the typedef is preferred. Consider the declarations:

dPS p1,p2;

tPS p3,p4;

The first expands to

which defines p1 to be a pointer to the structure and p2 to be an actual structure, which is probably not what you wanted. The second example correctly defines p3 & p4 to be pointers.

Obfuscated syntax

16. C allows some appalling constructs. Is this construct legal, and if so what does this code do?

int a = 5, b = 7, c;

Embedded Interview Questions

c = a+++b;

This question is intended to be a lighthearted end to the quiz, as, believe it or not, this is perfectly legal syntax. The question is how does the compiler treat it? Those poor compiler writers actually debated this issue, and came up with the “maximum munch” rule, which stipulates that the compiler should bite off as big a (legal) chunk as it can. Hence, this code is treated as:

Thus, after this code is executed, a = 6, b = 7 & c = 12;

If you knew the answer, or guessed correctly – then well done. If you didn’t know the answer then I would not consider this to be a problem. I find the biggest benefit of this question is that it is very good for stimulating questions on coding styles, the value of code reviews and the benefits of using lint.

Well folks, there you have it. That was my version of the C test. I hope you had as much fun doing it as I had writing it. If you think the test is a good test, then by all means use it in your recruitment. Who knows, I may get lucky in a year or two and end up being on the receiving end of my own work.

References:

  1. In Praise of the #error directive. ESP September 1999.
  2. Efficient C Code for Eight-Bit MCUs. ESP November 1988.

[1] Translation unit for the pedagogues out there.

[2] I’ve had complaints that these code fragments are incorrect syntax. This is correct. However, writing down syntactically correct code pretty much gives the game away.

[3] I’ve recently softened my stance on bit fields. At least one compiler vendor (IAR) now offers a compiler switch for specifying the bit field ordering. Furthermore the compiler generates optimal code with bit field defined registers – and as such I now do use bit fields in IAR applications.