C/C ++ written examination and interview questions 1-15

Source: Internet
Author: User


1. Find the return value of the following function (Microsoft)

Int func (X)
{
Int countx = 0;
While (X)
{
Countx ++;
X = x & (x-1 );
}
Return countx;
}
Assume x = 9999. Answer: 8
Train of Thought: Convert X to a binary system and check the number of contained 1.
2. What is "reference "? What should I pay attention to when declaring and using "reference?

A: A reference is the "alias" (alias) of a target variable. operations on an application are identical to operations on a variable. When declaring a reference, rememberInitialization
. After the reference declaration is complete, the target variable name has two names, namely, the original name and reference name of the target,You cannot use this reference name as an alias for other variable names.
. Declaring a reference is not a new variable. It only indicates that the reference name is an alias of the target variable name. It is not a data type, so the reference itself does not occupy the storage unit.Does not allocate storage units to references.
. You cannot create an array reference.
3. What are the features of using "Reference" as a function parameter?

(1)Passing a reference to a function has the same effect as passing a pointer.
. In this case, the parameter of the called function becomes an actual parameter variable or an alias of the object in the original main function, therefore, the operations on the parameters in the called function are the operations on the corresponding target object (in the main function.
(2)When a parameter passing a function is referenced, no copy of the real parameter is generated in the memory. It directly operates on the real parameter.
While using common variables to pass function parameters, when a function call occurs, you need to allocate storage units to the parameters. The parameters are copies of the real variables. If the objects are transmitted, the copy constructor will also be called. Therefore, when the data transmitted by parameters is large,It is better to use reference than to use common variables to pass parameters.

(3) Although using pointers as function parameters can achieve and use the reference effect, in the called functionSimilarly, you need to allocate storage units to the parameters.
And you need to repeat the operation in the form of "* pointer variable name", which can easily produce errors and the program reading is poor; on the other hand,At the call point of the main function, the variable address must be used as the real parameter. References are easier to use and clearer.

4. When do I need to use "regular reference "?

If you want to use references to improve program efficiency and protect the data transmitted to the function from being changed in the function, you should use regular references. The declaration method is often referenced:Const type identifier & reference name = target variable name;

Example 1
Int;
Const Int & RA =;
Ra = 1; // Error
A = 1; // correct
Example 2
String Foo ();
Void bar (string & S );
The following expression is invalid:
Bar (FOO ());
Bar ("Hello World ");
The reason is that both the Foo () and "Hello World" strings generate a temporary object. In C ++, these temporary objects are of the const type. Therefore, the above expression tries to convert a const type object to a non-const type, which is invalid.
The referenced parameter should be defined as const if it can be defined as Const.
5. Use "Reference" as the format, benefits, and rules of the function return value type?

Format: type identifier & function name (parameter list and type description) {// function body}
Benefit: do not generate a copy of the returned value in the memory. (Note: For this reason, it is not advisable to return a reference to a local variable. As the survival of the local variable ends, the corresponding reference will also become invalid, resulting in a runtime error!
Note:
(1)The local variable reference cannot be returned.
. For details, refer to item 31 of Objective C ++ [1. The main reason is that local variables will be destroyed after the function returns, so the returned reference becomes a reference of "no finger", and the program enters the unknown state.
(2)You cannot return a reference to the memory allocated by the new function.
. For details, refer to item 31 of Objective C ++ [1. Although there is no passive destruction of local variables, this situation (returning a reference to the memory allocated by the new function) faces other embarrassing situations. For example, if a reference returned by a function only appears as a temporary variable and is not assigned to an actual variable, the space pointed to by the reference (allocated by new) cannot be released,Cause Memory Leak
.
(3)Can return the reference of class members, but it is better to be const.
. This principle can be referred to item 30 of Objective C ++ [1. The main reason is that when an object attribute is associated with a business rule, its value assignment is often related to some other attributes or the state of the object, therefore, it is necessary to encapsulate the value assignment operation in a business rule. If other objects can obtain the non-constant reference (or pointer) of this attribute, a simple value assignment to this attribute will damage the integrity of business rules.
(4)Stream operator overload
The function of declaring the return value as "Reference:
Stream operators <and>,
These two operators are often used consecutively, for example, cout <"hello" <Endl; therefore, the return value of these two operators should be a stream reference that still supports these two operators. Other optional solutions include returning a stream object and returning a stream object pointer. HoweverTo return a stream object, the program must re-(copy) to construct a new stream object.
That is to say, two consecutive <operators are actually targeting different objects! This is unacceptable.If a stream pointer is returned, the <operator cannot be used consecutively.
. Therefore, returning a stream object reference is the only choice. This unique choice is critical. It illustrates the importance of reference and is irreplaceable. Maybe this is why the concept is introduced in C ++. Value assignment operator =. This operator can be used continuously like a stream operator, for example, x = J = 10; or (x = 10) = 100; the return value of the value assignment operator must be a left value, so that the value can be assigned. Therefore, it is referenced as the only return value choice of this operator.
Example 3
# I nclude <iostream. h>
Int & put (int n );
Int Vals [10];
Int error =-1;
Void main ()
{
Put (0) = 10; // use the put (0) function value as the left value, equivalent to Vals [0] = 10;
Put (9) = 20; // use the put (9) function value as the left value, which is equivalent to Vals [9] = 20;
Cout <Vals [0];
Cout <Vals [9];
}
Int & put (int n)
{
If (n> = 0 & n
<= 9) return Vals [N];
Else {cout <"subscript error"; Return Error ;}
}

(5)Among other operators, the reference: +-*/four Arithmetic Operators cannot be returned. They cannot return references.
, Objective C ++ [1] item23 discusses this issue in detail. The main reason is that these four operators do not have side effect. Therefore, they must construct an object as the return value. Optional solutions include: returning an object and returning a reference to a local variable, returns the reference of a newly assigned object and a static object reference. According to the preceding three rules that reference the returned value, both the 2nd and 3 schemes are rejected. Static object reference is caused by errors because (a + B) = (C + D) is always true. Therefore, only one object is returned.
6. What is the relationship between "reference" and polymorphism?
References are another method that can produce polymorphism effects except pointers. This means that a base class reference can point to its derived class instance.
Example 4
Class A; Class B: Class A {...}; B;A & ref = B;

7. What is the difference between "reference" and pointer?

After a pointer variable points to an object, it indirectly operates on the variable it points. When pointers are used in a program, the program has poor readability. The reference itself is the alias of the target variable, and the reference operation is the operation of the target variable. In addition, it is the difference between the ref passed to the function and the pointer mentioned above.
8. When do I need to "Reference "?

Stream operators <and>, return values of the value assignment operator =, parameters of the copy constructor, parameters of the value assignment operator =, and references are recommended in other cases.
Above 2-8 reference: http://blog.csdn.net/ysuncn/archive/2007/09/16/1787380.aspx


9. What is the difference between the structure and the union?

1. the structure and union are composed of multiple members of different data types, but at any time, only one selected member is stored in the Union (all members share an address space ), all members of the structure exist (the storage addresses of different members are different ).
2. assigning values to different members of the Union will be rewritten to other members. The original value of the members does not exist, but the assignment values to different members of the structure do not affect each other.
10. What is the output of the following question about "union?

A)
# I nclude <stdio. h>
Union
{
Int I;
Char X [2];
};

Void main ()
{
A. X [0] = 10;
A. X [1] = 1;
Printf ("% d", A. I );
}
Answer: 266 (low address, high address, memory usage is ox010a)
B)
Main ()
{
Union {
Int I;
Struct {
Char first;
Char second;
} Half;
} Number;
Number. I = 0x4241;
Printf ("% C/N", number. Half. First, mumber. Half. Second );
Number. Half. First = 'a ';
Number. Half. Second = 'B ';
Printf ("% x/N", number. I );
Getch ();
}
Answer: AB (0x41 corresponds to 'A', which is low; ox42 corresponds to 'B', which is high)

6261 (number. I and number. half share an address space)
11. The strcpy function prototype is known:Char * strcpy (char * strdest, const char * strsrc)
Here, strdest is the destination string and strsrc is the source string. Do not call the string library function of C ++/C. Compile the strcpy function.

Answer:
Char * strcpy (char * strdest, const char * strsrc)
{
If (strdest = NULL | strsrc = NULL)
Return NULL;
If (strdest = strsrc)
Return strdest;
Char * tempptr = strdest;
While (* strdest ++ = * strsrc ++ )! = '/0 ')
;
Return tempptr;
}
12. The string class is defined as follows:

Class string
{
Public:
String (const char * STR = NULL); // common Constructor
String (const string & Another); // copy the constructor
~ String (); // destructor
String & operater = (const string & RHs); // value assignment function
PRIVATE:
Char * m_data; // used to save strings
};


Try to write out the member function implementation of the class

.


Answer:
String: string (const char * Str)
{
If (STR = NULL) // If the strlen parameter is null, an exception is thrown.
{
M_data = new char [1];
M_data [0] = '/0 ';
}
Else
{
M_data = new char [strlen (STR) + 1];
Strcpy (m_data, STR );
}
}
String: string (const string & Another)
{
M_data = new char [strlen (another. m_data) + 1];
Strcpy (m_data, other. m_data );
}

String & string: Operator = (const string & RHs)
{
If (this = & RHs)
Return * this;
Delete [] m_data; // Delete the original data with a new memory
M_data = new char [strlen (RHS. m_data) + 1];
Strcpy (m_data, RHS. m_data );
Return * this;
}

String ::~ String ()
{
Delete [] m_data;
}
13. What is the function of ifndef/define/endif in the. h header file?

A: prevent this header file from being repeatedly referenced.
14. # What is the difference between I nclude <file. h> and # I nclude "file. H?

A: The former searches for and references file. h from the path of the standard library, while the latter works from the current

Path search and reference file. h.
15. Why should I add the extern "C" to call the function compiled by the C compiler in the C ++ program "?

First, as extern is a keyword in C/C ++ that indicates the range (visibility) of the function and global variable. This keyword tells the compiler,The declared functions and variables can be in this module or other modules.
Use


.
Extern "C" is a linkage declaration. Variables and functions modified by extern "C" are compiled and connected in C language, let's take a look at how C-like functions are compiled in C ++:

As an object-oriented language, C ++ supports function overloading, while Procedural Language C does not. The name of the function in the symbol library after being compiled by C ++ is different from that in the C language. For example, assume that the prototype of a function is:

Void Foo (int x, int y );
  


After the function is compiled by the C compiler, its name in the symbol library is _ Foo, while the C ++ compiler generates names such as _ foo_int_int (different compilers may generate different names, but all adopt the same mechanism, and the new name is called "mangled name ").

A name such as _ foo_int_int contains the function name, number of function parameters, and type information. c ++ relies on this mechanism.
Implementation


Function overload. For example, in C ++, the void Foo (int x, int y) and void Foo (int x, float y) functions generate different symbols, the latter is _ foo_int_float.

Similarly, variables in C ++ support both local variables and class member variables and global variables. The class member variables of the program written by the user may have the same name as the global variables, which are distinguished. In essence, the compiler uses a unique name for the variables in the class when compiling, similar to the function processing. This name is different from the global variable name with the same name in the user program.

Connection method when extern "C" is not added

Suppose in C ++, the header file of module A is as follows:

// Module A header file modulea. h
# Ifndef module_a_h
# Define module_a_h
Int Foo (int x, int y );
# Endif


Reference this function in Module B:

// Module B implements the file moduleb. cpp
# I nclude "modulea. H"
Foo (2, 3 );
  


In fact, in the connection phase, the connector looks for symbols such as _ foo_int_int from the target file modulea. OBJ generated by module!

Compilation and Connection Methods After the extern "C" clause is added

After the extern "C" statement is added, the header file of module A is changed:

// Module A header file modulea. h
# Ifndef module_a_h
# Define module_a_h
Extern "C" int Foo (int x, int y );
# Endif


In Module B's implementation file, Foo (2, 3) is still called. The result is:
(1) When module A compiles and generates the foo target code, it does not perform special processing on its name and uses the C language;


(2) When the connector looks for the Foo (2, 3) call for the target code of Module B, it looks for the unmodified symbol name _ Foo.

If the function in module A declares that foo is of the extern "C" type, and Module B contains the extern int Foo (INT X, int y ), module B cannot find the function in module A, and vice versa.

Therefore, the true purpose of the statement "extern" C "can be summarized in one sentence (any language

The birth of any syntax feature in is not random and comes from the real world.

. We are thinking about the problem

We should not just look at how the language is made, but also ask why it is doing so and what the motivation is, so that we can better understand many questions ):Implementation

Mixed Programming of C ++ and C and other languages

.

Understand the motivation for setting up extern "C" in C ++. Next we will analyze the general usage of extern "C ".

TIPS:
Usage of extern "C"


(1)Reference functions and variables in C language in C ++, and include the C Language header file (for example, cexample. h)
The following operations are required:
Extern "C"
{
# I nclude "cexample. H"
}
In the header file of C language,The external function can only be specified as the extern type.
,The C language does not support the extern "C" statement.
When the. c file contains extern "C", a compilation syntax error occurs.

C ++ references the source code of the three files contained in the C function example project as follows:

# Ifndef c_example_h
# Define c_example_h
Extern
Int add (int x, int y );
# Endif

# I nclude "cexample. H"
Int add (int x, int y)
{
Return X + Y;
}

// C ++ implementation file, call Add: cppfile. cpp

Extern "C"

{
# I nclude "cexample. H"
}
Int main (INT argc, char * argv [])
{
Add (2, 3 );
Return 0;
}
If C ++ calls a. dll written in C language, when it includes the header file of. dll or the declared interface function, it should add extern "C "{}.

(2)When C references functions and variables in C ++, the header file of C ++ needs to add extern "C ", however, you cannot directly reference this header file that declares extern "C" in C. You should only declare the extern "C" function defined in C ++ as the extern type.

C references the source code of the three files contained in the C ++ function example project as follows:
//C ++ header file
Cppexample. h
# Ifndef cpp_example_h
# Define cpp_example_h
Extern "C" int add (int x, int y );
# Endif

//C ++ implementation file
Cppexample. cpp
# I nclude "cppexample. H"
Int add (int x, int y)
{
Return X + Y;
}

Extern
Int add (int x, int y );
Int main (INT argc, char * argv [])
{
Add (2, 3 );
Return 0;
}
15 for answers to questions, see 《
Deep Exploration of the meaning of extern "C" in C ++

"

Note:

In general, the function and global variables referenced by this module to other modules are declared with the keyword extern in the module header file. For example, if Module B wants to reference the global variables and functions defined in module A, it only needs to include the header file of module.
You can.


. In this way, when Module B calls a function in module A, although Module B cannot find the function in the compilation phase, it does not report an error.
Connection


Find this function from the target code generated by module A in the phase

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.