Implement strlen functions without using intermediate Variables

Source: Internet
Author: User

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;
}

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.