2009 Tencent campus recruitment pen questions: without using intermediate variables to evaluate the const string length, the strlen function is used to evaluate the string length library. The function interface declaration is as follows: int strlen (const char * p );
Train of Thought Analysis:
"No intermediate variables" means that programmers cannot apply for memory explicitly, that is, they cannot apply for local variables or dynamic memory. If the function automatically applies for stack memory, uses registers to store variables, or uses immediate number addressing as a constant, it is equivalent to "no intermediate variable ". From the perspective of function prototype, if the returned value is int, you must store this value in one place within the function, either a constant or a register. If the length is not 1, it cannot be obtained once. It indicates that a recursive call is required. In this way, the function automatically applies for stack memory, which is equivalent to "no intermediate variable" for programmers. The value returned in the middle is automatically saved in the register and copied to the int during the last return. C ++ also has the concept of temporary objects, which are all objects automatically applied by the compiler in the stack during program running. They are invisible to programmers and are equivalent to "no intermediate variables"
This problem occurs when constants are used, or the application of variables is handed over to the compiler and automatically applied in the stack during recursion.
[Cpp]
# Include <iostream>
Using namespace std;
Int mystrlen (const char * str)
{
If (str = NULL)
Return 0;
If (* str! = '\ 0 ')
Return 1 + mystrlen (++ str );
Else
Return 0;
}
Void main ()
{
Char * str = "Diaoyu islands belong to china ";
Cout <mystrlen (str) <endl;
}