Learn the embedded No. 04 episode with Brother Tao: An interview question to measure your C language skills

Source: Internet
Author: User

Hello everyone, I am Tao elder brother, Welcome to read "With Tao elder brother learn embedded together" The No. 04 episode, today chat face question.

In embedded C-language interview questions, you will often see macro-defined questions. For example: Define a macro to find the maximum number of two numbers. Do not underestimate this exam, although simple, but it is a constant trap, always test your C language programming skills! According to your answer, the interviewer must have a different impression of you. Let's take a look at the answers to each of the different versions.

Qualified

For students who have studied C, writing this macro is basically not a difficult task, and can be accomplished using the conditional operator:

#define  MAX(x,y)  x > y ? x : y

This is the most basic C language grammar, if not even this can not be written, it is estimated that the scene will be more awkward. In order to alleviate embarrassment, the interviewer will generally say to you: "Young man, you are very good, go back to the news, there is news, we will inform you!" At this time, you should understand: no longer wait, hurriedly read this article, and then face the next. This macro can be written out, do not think you are very bull X, because it can only show that you have the basis of C language, but there is a lot of room for progress. For example, we write a program that verifies that the macros we have defined are correct:

#define MAX(x,y) x > y ? x : yint main(void){    printf("max=%d",MAX(1,2));    printf("max=%d",MAX(2,1));    printf("max=%d",MAX(2,2));    printf("max=%d",MAX(1!=1,1!=2));    return 0;}

Test the program, we are sure to put all kinds of possible situations to test it again. This is not, the Test line 4th statement, when the macro parameter is an expression, found that the actual result is max=0, and we expect the result max=1 not the same. This is because, after the macro is expanded, it becomes this way:

printf("max=%d",1!=1>1!=2?1!=1:1!=2);

Because the comparison operator > has a priority of 6, greater than! = (priority 7), the expanded expression, the order of operations has changed, and the result is different from what we expected. To avoid this expansion error, we can add a brace () to the macro's argument to prevent the expression from changing the order of operations after it has been expanded. Such a macro can be counted as a qualified macro:

#define MAX(x,y) (x) > (y) ? (x) : (y)

Medium

The above macro can only be qualified, but there are still loopholes. For example, we use the following code to test:

#define MAX(x,y) (x) > (y) ? (x) : (y)int main(void){    printf("max=%d",3 + MAX(1,2));    return 0;}

In the program, we print the value of the expression 3 + MAX (1, 2) and the expected result should be 5, but the actual result is 1. After we unfolded, we found that there were also problems:

3 + (1) > (2) ? (1) : (2);

Since the precedence of operator + is greater than the comparison operator, the expression becomes 4>2?1:2 and the result is 1. At this point we should continue to modify this macro:

#define MAX(x,y) ((x) > (y) ? (x) : (y))

Use parentheses to wrap the macro definition so that it avoids destroying the entire expression's order of operations when an expression contains both a macro definition and other high-priority operators. If you can write this step, indicating that you are better than the previous interview qualified students, the front of the classmate has gone back to wait for news, we continue to interview the next round.

Good

The above macro, while addressing the problem of operator precedence, still has a certain vulnerability. For example, we use the following test program to test our defined macros:

#define MAX(x,y) ((x) > (y) ? (x) : (y))int main(void){    int i = 2;    int j = 6;    printf("max=%d",MAX(i++,j++));    return 0;}

In the program, we define two variables I and J, then compare the size of the two variables and do the self-increment operation. The actual run result finds Max = 7 instead of the expected result max = 6. This is because the variables I and J do two self-increment operations after the macro expands, resulting in a value of 7 being printed out.

What do you do when you encounter this situation? At this point, the statement expression should be played. We can use statement expressions to define the macro, define two temporary variables in the statement expression, separate the values of I and J, and then compare, thus avoiding two self-increment, self-reduction problems.

#define MAX(x,y)({         int _x = x;            int _y = y;            _x > _y ? _x : _y; })int main(void){    int i = 2;    int j = 6;    printf("max=%d",MAX(i++,j++));    return 0;}

In the statement expression, we define 2 local variables _x, _y to store the values of the macro parameters x and y, and then use _x and _y to compare the sizes, thus avoiding the 2 self-multiplication problems that I and J bring.

You can persist to this level, and write such a BGM of the macro, the interviewer may have given you the willingness to offer. But at this moment, don't be proud! In order to completely eliminate the interviewer's psychological concerns, we need to continue to optimize the macro.

Excellent

In the above macro, the two temporary variable data types we define are int type and can only compare data of two integer types. That for other types of data, you need to redefine a macro, so it's too much trouble! We can continue to modify it based on the macro above so that it can support any type of data compare size:

#define MAX(type,x,y)({         type _x = x;            type _y = y;            _x > _y ? _x : _y; })int main(void){    int i = 2;    int j = 6;    printf("max=%d\n",MAX(int,i++,j++));    printf("max=%f\n",MAX(float,3.14,3.15));    return 0;}

In this macro, we add a parameter: type, which specifies the type of temporary variable _x and _y. This way, when we compare the size of two numbers, we can compare any type of data by simply passing the type of 2 data as a parameter to the macro. If you can write such a macro in the interview, the interviewer will certainly be very happy, he will usually tell you: young man, wait, HR will talk to you about the treatment.

Can you be more awesome?

If you want to get a higher salary, pay better, you should not be proud at this time, you should be big hand wave: Wait, I can even better!

In the macro definition above, we have added a type parameter to be compatible with different data types, and at this point we should save this for the sake of salary. How do you do that? Using TypeOf, TypeOf is a new GNU C keyword, used to get the data type, we do not have to pass in, let typeof directly get!

#define max(x, y) ({        typeof(x) _x = (x);     typeof(y) _y = (y);     (void) (&_x == &_y);    _x > _y ? _x : _y; })

In this macro definition, the TypeOf keyword is used to get the two parameter types of a macro. Dry goods in (void) (&x = = &y), this sentence, is simply a genius design! One is to give users a warning, for different types of pointer comparisons, the compiler will give a warning that two data types are different; second, when two values are compared, the results of the comparison are not used, some compilers may give a warning, add a (void), you can eliminate this warning!

At this moment, the interviewer sees you this macro, estimated will take a breath: obediently, really is alitily, this guy is better than me! You wait, HR will come over and talk to you about your salary!

Congratulations, you got the offer!

This article is based on the "C Language embedded Linux Advanced Programming" phase 5th: C Standard and the C syntax extension in the Linux kernel part video adaptation. "With Tao Brother learn embedded", will continue to share with you embedded technology, learning methods, learning route, job interview, etc., interested in joining the embedded technology Exchange Group: 475504428, or the public number: Otaku Tribe (Armlinuxfun). Or about the 51CTO college my personal page: http://edu.51cto.com/lecturer/10824150.html

Learn the embedded No. 04 episode with Brother Tao: An interview question to measure your C language skills

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.