Use a knife to kill people, and use no intermediate variable to implement strlen
Sailor_forever sailing_9806@163.com reprint please note
Http://blog.csdn.net/sailor_8318/archive/2008/10/13/3071048.aspx
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:
In a string, the last Terminator '/ 0' But here the parameter is const, read-only, so we cannot beat his idea
It is basically impossible for a function to run without occupying memory unless registers are used. "Do not use intermediate variables"ProgrammerThe requested memory cannot be displayed, that is, local variables or dynamic memory cannot be applied.
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"
Another typical topic that does not apply for any variable is: reverse string (Http://blog.csdn.net/sailor_8318/archive/ 2008/10/11 /3058240. aspx)
This problem occurs when constants are used, or the application of variables is handed over to the compiler for automatic application in the stack during the recursion process, that is, the knife is used to kill people, no matter what I do, I just made soy sauce, haha.
//////////////////////////////////////// //////////////////////////////////
Int nomallocstrlen (const char * Str)
{
If (STR = NULL)
{
Return 0;
}
If (* Str! = '/0 ')
{
Return 1 + nomallocstrlen (++ Str );
}
Else
Return 0;
}
Int main ()
{
Const char * P = "Hello! ";
Int A = nomallocstrlen (P );
If (A = strlen (p ))
{
Printf ("nomallocstrlen is well done! /N ");
}
Else
{
Printf ("error! /N ");
}
}