A 'C' Test: The 0x10 Best Questions for Would-Be Embedded Programmers
Nigel Jones
Pencils Up, Everyone. Here's a test to identify Potential Embedded Programmers or Embedded Programmers with Potential
A n 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 Informative for Both The Interviewer and Interviewee. Furthermore, When Given Outside The press of an interview situation
From the interviewee's perspective, you can learn a lot about the person who 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 Whather I Want The Job in Question.
From the interviewer's perspective, a test can reveal several things about the candidate. Primarily, you can determine the level of the candidate's knowledge of C. However, it's also 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 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 the store; 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 ow w uses, feel free to assign score.
Preprocessor 1. Using The #define Statement, How Would You Declare A Manifest Constant That Returns The Number of Seconds in a year? Disreg Leap Years in your answer.
#define seconds_per_year
(60 * 60 * 24 * 365) UL
I'm looking for several things here:
Basic Knowledge of the #define syntax (for example, no semi-color to pieenthesize, and so on)
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 yourselfA 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 Variable As a long
As A Bonus, if You Modified The Expression With A UL (INDICATINE OFFLONED), THEN Are Off to a Great Start. And Remember, First Impressions Count!
2. Write the "Standard" min macro-That IS, A Macro Takes Two Arguments And Returns The Smaller of The Two Arguments.
#define min (a, b)
((A)
<
= (B)? (A): (b))
The purpose of this Question is to test the folload:
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
Knowledge of the ternary conditional operator. This operator exists in C because it allows the compiler to 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
Understanding of the need to very carefully parenthesize arguments to macros
I Also Use this Questions To Start A Discussion On The Side Effects of Macros, for Example, 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 do not. If you do not, see Reference 1. This question is useful for differentiating between normal folks and the nerds. Only the nerds actually read the appendices of C textbooks to find out about such things. Of course, if you are not looking for a nerd, the candidate better hope she does not know the answer.Infinite loops 4. Infinite loops often arise in embedded systems. How does you code an infinite loop in C ?
There Are Several Solutions To this question. My Preferred Solution IS:
While (1)
{
?
Many Programmers Seem to Prefer:
For (;;)
{
?
This construct puzzles me because the syntax does not exactly spell out what's 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 Haven't Thought About It Since," IT Tells Me Something (BAD) About Them.
A third solution is to use a goto:
Loop
:
...
goto
Loop
;
Candidates Who Propose This Are Either Assembly Language Program (Which is probably good), or else the isy.....................
Data Declarations 5. Using The Variable A, Give Definitions for the Following: a) An Integer B) A Pointer TO A POINTER TO ANTEGER D) AN ARRAY OF 10 INTEGERS E) an Array of 10 Pointers to integers f) A pointer to an array of 10 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) INTEGER C) INT ** A; // a Pointer TO A Pointer to an INTEGER D) INTEGER D) Int A [10] ; // ARRAY OF 10 INTEGERS E) INT * a [10]; // ARRAY OF 10 POINTERS TO INTEGERS F) INT (* a) [10]; // a Pointer to an Array Of 10 Integers G) INT (* a) (int); // a Pointer to a function a Takes an integer argument and returns an integer h) int (* a [10]) (int); // an array of 10 Pointers to Functions Take an integer argument and return an integerPeople 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 I'm being interviewed. Consequently, I make sure I know the answers, at least for the few hours of the interview. Candidates who do not know all the answers (or at Least MOST OF THEM) Are Simply Unprepared for the Interview. if They CA N't be prepared for the interview, What Will The 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 variable declared static wely of a function maintains its value betWeen function invocations
A variable declared static within a module, (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
Functions Decland Static WTATINIIN A MODULE MAY ONLY BE CALED BY Other Functions With Module. That IS, The Scope of The Function Is Localized to the Module With IT IT IS Declared
Most candidates get the first part correct. A reasonable number get the second part correct, while a pitiful number understand the third answer. This is a serious weakness in a candidate, since he obviously does not understand the importance and benefits of localizing the scope Of Both Data and Code.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 can not 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 detaild answer, read saks' columns-carefully!)
IF The Candidate Gets The Answer Correct, I'll Ask Him The Supplemental Questions:
What Do The Following 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 (That IS, The Integer ISN'T Modifiable, But The Pointer IS). The Fourth Declares a to be a const pointer to an integer (That IS, 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 (That IS, 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, you might wonder why I put so much emphasis on const, since it is easy to write a correctly functioning program without ever using it I have several reasons:. 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 message left by other people you'll quickly learning SETRA PIECE OF INFORMATION. (Of Course, Programmers Who Use Const, Rarely Leave a Mess for Others to Clean Up.)
Const Has The Potential for Generating Tighter Code by Giving The Optimizer Some Additional Information
Code That Uses Const Liberally is inherently protected by the Compiler Against INADVERTENT CODING CONSTRUCTS That Result In Parameters Being Changed That Should 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: Hardware Registers in Peripherals (for Example, Status Registers)
Non-Automatic Variables Reference With Interrupt Service Routine
Variables Shared by Multiple Tasks in a Multi-Threaded Application
Candidates who do not know the answer to this question are not 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 additional questions.:
Can a parameter be Both Const and Volatile? Explain.
Can a pointer be volatile? Explain.
What's WRONG WITH THE FOLLOWING FUNCTION ?:
INT Square (Volatile Int * PTR)
{
Return * ptr * * PTR;
}
The Answers Are As Follows:
YES. AN EXAMPLE IS A Read-Only Status Register. It is volatile because it can changely, it is const because the program shop, attempt to modify it
Yes, Althought this is not very common. An Example Is When An Interrupt Service Routine Modifies a Pointer To A Buffer
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)
{
INT A, B;
a = * PTR;
B = * PTR;
Return a * b;
}
. Because it's 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)
{
Int a;
a = * PTR;
Return A * a;
}
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 shouth be unmodified.
THESE Are The Three Basic Responses To this question:
No IDea. The Interviewee Cannot Have Done Any Embedded Systems Work
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 chips 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!
Use #defines and bit masks. This is a highly portable method and is the one what should be used. My Optimal Solution to this questionm 10
#define bit3 (0x1
<
<
3)
Static Int A;
Void set_bit3 (void) {a | = bit3;
}
Void clear_bit3 (void) {
A & = ~ bit3;
}
Some people prefer to define a mask together with manifest constants for the set and clear values This is also acceptable The element that I'm looking for is 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 is required to set an integer variable at the absolute address 0x67a9 to the value 0xaa55. The compiler is a pure ANSI it 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..:
INT * PTR;
PTR = (int *) 0x67a9;
* PTR = 0xAA55;
A more obscure approach is:
* (int * const) (0x67a9) = 0xAA55;
Even if your taste runs More to the second solution, i suggest the first solution.
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 keyword is __interrupt. The following code uses __interrupt to define an interrupt service routine (ISR). 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 hard to know where to start:
ISRS Cannot Return A Value. If you do't understand THIS, You aren't hiredisrs. See the first item for your employment Prospects if you med
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 can not do floating point in an ISR. Furthermore, given that a general rule of thumb Is this isrs shop be short and sweet, one wonders about the Wisdom of doing floating-point math here
In a vein similar to the third point, printf () often has problems with reentrancy and performance. If you missed points three and four, I would not be too hard on you. Needless to say, if you got these last two points, 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? 0 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, you are perilously close to not getting the job.
13. Comment on The Following Code FRAGMENT.
Unsigned int zero = 0;
Unsigned int compzero = 0xfff; / * 1's complement of zero * /
On Machines Where An Int Is Not 16 Bits, this Will Be IncorRect. It Should Be Coded:
Unsigned int compzero = ~ 0;
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're on a roll and having a good time. If it's obvious that the candidate is not 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 do still 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, and so on. This topic has been covered extensively in ESP, mainly by PJ 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 folowing code fragment output outprut and why?
Char * PTR;
IF ((ptr = (char *) malloc (0)) == NULL)
Else
PUTS ("Got A Null Pointer";
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! That is, the above code will output "Got a valid pointer." I use this to start a discussion on whether the interviewee thinks this is the correct thing for the library routine to do. Getting the right answer here is not nearly 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..:
#define DPS Struct S *
Typedef struct s * tps;
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 who 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:
Struct S * P1, P2;
Which defines p1 to be a pointer to the structure and p2 to be an actual structure, Which is probably not what you would wanted. The second example correctly defines p3 and p4 to be pointers.
Obscure Syntax 16. C Allows Some Appalling Constructions. Is this Construct Legal, Andi So What Does this code do?
INT A = 5, B = 7, C;
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 (AND LEGAL) A Chunk As It Can Hence, this Code Is Treated AS: C = A B;
Thus, after this code is executed, A = 6, b = 7, and c = 12.
If you knew the answer, or guessed correctly, well done. If you did not know the answer then I would not consider this to be a problem. I find the greatest benefit of this question is that it is 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 Taking It As I Had Writing It. If you think the test is a good test, dam, one Recruitment. WHO KNOWS, I May Get Lucky In a year or two and end up being on the receiving end of my own work.
Nigel Jones Is A Consultant Living in
Maryland
...................................