An in-depth analysis of common face questions for C + + programmers (2)

Source: Internet
Author: User

Excerpt from: http://blog.csdn.net/zhoudengqing 3. Internal problems Question 1:Given the bool,int,float, the IF statement of the pointer variable compared to the "0 value" (assuming that the variable is named Var) Answer:BOOL Variant: if (!var) int variable: if (var==0) float type variable: const FLOAT Epsinon = 0.00001;if ((x >=-Epsinon) && (x <= EPS Inon) pointer variable: if (var==null) Anatomy:To examine the "internal strength" of the 0 value judgement, the BOOL type variable 0 judgment can be written as if (var==0), and the int variable can also be written as if (!var), pointer variable judgment can also be written as if (!var), the above notation, although the program can be correctly run, But failed to express the meaning of the program clearly. In general, if you want the if to determine the "true", "false" of a variable, you should use if (Var), if (!var), to indicate that it is "logical" judgment, if you use if to determine a numeric variable (short, int, long, etc.), should be used if (var==0), It is a good programming habit to use the IF (var==null) to judge the pointer when it is compared with 0 for "numerical value". Floating-point variables are not accurate, so float variables cannot be "= =" or "! = "In comparison with numbers, you should try to convert them into" >= "or" <= "forms. If written as if (x = = 0.0), then the sentence is wrong, 0 points. Question 2:The following is a 32-bit C + + program under Windows NT, please calculate sizeof's value void Func (char str[100]) {sizeof (str) =?} void *p = malloc (+); sizeof (p) =? Answer:sizeof (str) = 4sizeof (P) = 4 Anatomy:Func (char str[100]) function in the array name as a function parameter, in the function body, the array name loses its own connotation, just a pointer, in the loss of its connotation at the same time, it also lost its constant characteristics, can be self-increment, self-reduction and other operations, can be modified.   The nature of the array name is as follows: (1) The array name refers to a data structure, which is an array; for example: Char str[10];cout << sizeof (str) << Endl; The output result is 10,STR data structure char[10].   (2) The array name can be converted to a pointer to its reference entity, and is a pointer constant, can not be self-increment, self-reduction and other operations, can not be modified; char str[10];str++; Compilation error, indicating that STR is not an lvalue (3) array name as a function parameter, is reduced to a normal pointer. Under the Windows NT 32-bit platform, the length of the pointer (memory size) is 4 bytes, so sizeof (str) and sizeof (p) are 4. Question 3:Write a "standard" macro min, this macro enters two parameters and returns the smaller one.          Also, what happens when you write the following code? least = MIN (*p++, b); Answer:#define MIN (A) (A) <= (B)? (A): (b) MIN (*p++, b) will produce macro side effects Anatomy:This question mainly examines the interviewer's use of the macro definition, which can implement functions similar to a function, but it is not a function at all, but the "parameters" in the brackets in the macro definition are not real arguments, and the "parameters" are replaced one-to-a-time when the macro is expanded. Programmers should be very careful with the use of macro definitions, paying particular attention to two questions: (1) carefully surround the "parameters" in the macro definition with the entire macro in parentheses. So, strictly speaking, the following answers: #define MIN (A) (A) <= (B)? (a): (b) #define MIN (a <= B) A:B) should be sentenced to 0 points; (2) Prevent macro side effects. Macro definition # define MIN (A) (A) <= (B)? (A): (b) The result of the effect on min (*p++, B) was: ((*p++) <= (b)? (*p++): (*p++)) This expression can have side effects, and pointer p will do three + + self-increment operations. In addition, another 0-point answer is: #define MIN (A, a) ((A) <= (B)? (A): (B)); This solution adds ";" to the macro definition, showing that the writer's concept of the macro is vague and can only be ruthlessly sentenced to 0 points and eliminated by the interviewer. Question 4:Why do standard header files have a structure similar to the following?   #ifndef __incvxworksh #define __incvxworksh #ifdef __cplusplus extern "C" {#endif/*...*/#ifdef __cplusplus } #endif #endif/* __incvxworksh */ Answer:The compiler macro #ifndef __incvxworksh#define __incvxworksh#endif in the header file is used to prevent repeated references. As an object-oriented language, C + + supports function overloading, whereas programming language C is not supported. The function is compiled in C + + with a different name in the symbol library than in the C language. For example, suppose a function is prototyped as: void foo (int x, int y), the function is compiled by the C compiler in the symbol library with the name _foo, and the C + + compiler produces names like _foo_int_int. _foo_int_int such a name includes the number of function names and functions and the type of information, C + + is the mechanism to implement function overloading. In order to achieve C and C + + mixed programming, C + + provides a C connection to exchange the specified symbol extern "C" to solve the name matching problem, the function declaration is preceded by the extern "C", the compiler will follow the C-language method to compile the function as _foo, so C can call C + + function. Question 5:Write a function that moves the string consisting of a char to the right of N. For example, the original is "Abcdefghi" if n=2, after the shift should be "hiabcdefgh" function head is this://PSTR is a pointer to the string ending with ' \ '//steps is required to move nvoid loopmove (char * pStr, int steps) {//Please fill ...} Answer:Correct solution 1:void Loopmove (char *pstr, int steps) {int n = strlen (PSTR)-steps;       Char Tmp[max_len];    strcpy (tmp, PSTR + N);       strcpy (tmp + steps, PSTR);    * (tmp + strlen (pStr)) = ' + '; strcpy (PSTR, TMP);}    Correct solution 2:void Loopmove (char *pstr, int steps) {int n = strlen (PSTR)-steps;       Char Tmp[max_len];      memcpy (tmp, PSTR + N, steps);        memcpy (pStr + steps, PSTR, N);   memcpy (PSTR, TMP, steps); } Anatomy:This paper mainly examines the interviewer's proficiency in standard library functions, and when needed, referencing library functions can greatly simplify the work of programming. The most frequently used library functions are: (1) strcpy (2) memcpy (3) memset Question 6:The WAV file format is known as the following table, open a WAV file, organize the WAV file header with the appropriate data structure and parse the information in WAV format. Wave File Format Description table
  Offset address Number of bytes Data type Content
File header 10) 4 Char "RIFF" flag
14) 4 Int32 File length
08H 4 Char "WAVE" logo
0CH 4 Char "FMT" flag
10H 4 Transition bytes (variable)
14H 2 Int16 Format category
16H 2 Int16 Number of channels
18H 2 Int16 Sample rate (number of samples per second), indicating the playback speed of each channel
1CH 4 Int32 Waveform audio data transfer rate
20H 2 Int16 Number of data block adjustments (in bytes)
22H 2 Number of data bits per sample
24H 4 Char The data marker
28H 4 Int32 Length of voice data
Answer:Defines the WAV file format as a struct waveformat:typedef struct tagwaveformat{             char Criffflag[4];        uin32 nFileLen;            char cwaveflag[4];              char Cfmtflag[4];        char Ctransition[4];             uin16 NFormatTag;            uin16 nchannels;         uin16 nsamplespersec;              uin32 Navgbytespersec;            uin16 Nblockalign;             uin16 Nbitnumpersample; &nBsp;       char Cdataflag[4];       uin16 naudiolength;    waveformat; Assuming that the WAV file content is read out and stored in a memory cell that starts at the pointer buffer, the code for parsing the file format is simple, for:waveformat   waveformat;memcpy (&waveformat, buffer,sizeof (Waveformat)); By accessing the members of the Waveformat directly, you can obtain the format information for a particular WAV file. Anatomy:Question 6 examines the ability of the interviewer to organize the data structure, the experienced program designer will organize the members of a whole group into a structure, using the pointer type conversion, can use memcpy, memset and other functions directly to the structure of the address, the overall operation of the structure. Through this question can see the interviewer's programming experience is rich. Question 7:Write the constructor, destructor, and assignment functions of the class string, the prototype of the known class string is: Class string{public:string (const char *STR = NULL);//General Constructor St Ring (const String &other); Copy constructor ~ String (void); destructor string & operate = (const string &other); Assignment function Private:char *m_data; Used to save the string}; Answer:Ordinary constructor string::string (const char *str) {       if (str==null)         {                m_data = new Char[1];   Score points: Automatically apply for empty string to hold the end of the sign ' + ' empty                                               //Plus points: judgment on M_data plus null                 *m_data = ';  '       }           else        {        int length = strlen ( STR);         m_data = new char[length+1];   If you can add &nbsP null  judgment is better         strcpy (m_data, str);        }}//the destructor for String string::~string (void) {       delete [] m_ Data   or delete m_data;} Copy constructor string::string (const String &other)  //  score point: input parameter is const type {             int length = strlen (other.m_data);        m_data = new char[length+1]; //Plus points: m_data plus null  judgment         strcpy (M_data, other.m_data);     }//Assignment function string & string::operate = (const String &other)/ /  score points: input parameter is const type {            if (this = & Other)                  // Score points: Check self-assignment &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;   return *this;          delete [] m_data;            //Scoring points: releasing the original memory resources         int length = strlen (other.m_data);              m_data = new char[length+1]; //Plus points: m_data plus null  judgment         strcpy (M_data, other.m_data);           return * this;    //Score points: Returns a reference to this object} Anatomy:The interviewer, who can write the constructor, copy constructor, assignment function, and destructor of the string class correctly, has at least 60% of the basic skills of C + +! The pointer class member variable m_data is included in this class, and it is important to reload the copy constructor, assignment function, and destructor when the class includes pointer class member variables, which is both a basic requirement for C + + programmers and a special emphasis in effective C + +. Study this class carefully, pay special attention to annotate points and points of significance, so that more than 60% of C + + basic Skills! Question 8:Please say the static and const keywords as many functions as possible Answer:The static keyword has at least the following n functions: (1) The function body static variable is scoped to the function body, unlike the auto variable, the memory of the variable is allocated only once, so its value remains the last value at the next call ; (2) The static global variable within the module can be accessed by the function used within the module, but cannot be accessed by other functions outside the module, and (3) the static function within the module can only be called by other functions within the module, and the use of the function is limited to the module in which it is declared. ; (4) A static member variable in a class is owned by the entire class, has only one copy of all objects of the class, and (5) the static member function in the class is owned by the entire class, which does not receive the this pointer, and therefore can only access static member variables of the class. The CONST keyword has at least the following n functions: (1) to prevent a variable from being changed, you can use the Const keyword. When defining the const variable, it is often necessary to initialize it, since there is no chance to change it again; (2) for pointers, you can specify that the pointer itself is a const, or that the pointer refers to a const or both, and that both are specified as const; (3) In a function declaration, A const can modify a formal parameter to indicate that it is an input parameter and cannot change its value inside a function, (4) for a member function of a class, if it is specified as a const type, it is a constant function and cannot modify the member variable of the class, and (5) for the member function of the class, Sometimes it is necessary to specify that its return value is a const type so that its return value is not "left value". For example: const ClassA operator* (const classa& a1,const classa& A2); The return result of operator* must be a const object. If not, such a perverted code will not compile an error: ClassA A, B, C; (A * b) = C; The result assignment operation for A*b (A * b) = C is clearly not in line with the programmer's original intention, nor does it make any sense. Anatomy:Are you surprised? The little static and the const actually have so many functions, how many can we answer? If you can only answer one or two, then you really have to retreat and cultivate well. This question can examine the interviewer's mastery of programming knowledge is primary, intermediate or relatively deep, without a certain breadth and depth of knowledge, it is impossible to give a comprehensive answer to this question. Most people can only answer some of the features of the static and const keywords. 4. Technical questions Question 1:Please write a C function, if the processor is Big_endian, then return 0, if Little_endian, then return 1 Answer:int Checkcpu () {{union w {int A;            Char b;            C            C.A = 1;     return (C.B = = 1); }} Anatomy:Embedded system developers should be well aware of the Little-endian and Big-endian models. CPUs in Little-endian mode are stored in the operands from low to high byte, while the Big-endian mode stores the operands from high to low bytes. For example, the 16bit wide number of 0x1234 in Little-endian mode CPU memory (assuming that it is stored from the address 0x4000) is as follows:
Memory address 0x4000 0x4001
Store content 0x34 0x12
In Big-endian mode, the CPU memory is stored in the following way:
Memory address 0x4000 0x4001
Store content 0x12 0x34
The 32bit wide number of 0x12345678 in Little-endian mode CPU memory (assuming that it is stored from the address 0x4000) is as follows:
Memory address 0x4000 0x4001 0x4002 0x4003
Store content 0x78 0x56 0x34 0x12
In Big-endian mode, the CPU memory is stored in the following way:
Memory address 0x4000 0x4001 0x4002 0x4003
Store content 0x12 0x34 0x56 0x78
The Union union is stored in the order that all members are stored from the low address, and the interviewer's solution takes advantage of this feature to easily get the CPU to read or write to memory in Little-endian or Big-endian mode. If anyone can give this answer on the spot, it's a genius programmer. Question 2:Write a function that returns the value of 1+2+3+...+n (assuming that the result does not exceed the range of the long integer variable) Answer:int Sum (int n) {return ((long) 1 + N) * N/2; or return (1l + N) * N/2;} Anatomy:For this question, it can only be said that perhaps the simplest answer is the best answer. The following answer, or based on the following solutions to optimize, no matter how "toss", its efficiency can not be compared with direct return (1 L + N) * N/2!  int sum (int n) {long Sum = 0;  for (int i=1; i<=n; i++) {sum + = i; } return sum;} So programmers need to be sensitive to the use of mathematics and other knowledge in programming.

An in-depth analysis of common face questions for C + + programmers (2)

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.