Hi,
Is it possible to implement a strlen function without declaring any local or global variable ?
Thanks,
Hi,
Is it possible to implement a strlen function without declaring any local or global variable ?
Thanks,
Here's one example:
const char* TermPos(const char* Data)
{
while(Data[0]) ++Data;
return Data;
}
int StrLen(const char* Data)
{
return TermPos(Data) - Data;
}
Here's another example:
int StrLen(const char* Data)
{
struct TermPos{
const char* GetTermPos(const char* Data){while(Data[0]) ++Data;return Data;};
};
return TermPos().GetTermPos(Data) - Data;
}
Great.
Thanks,
Here's a real simple one using recursion.
int StrLen(const char* Data)
{
if (!Data || !Data[0]) return 0;
return 1 + StrLen((++Data));
}
Then there's the solution that requires neither recursion nor two functions:
although it's rather pathological. It's syntactically correct, but would end up being larger than the address space in which it operated, assuming you could even compile it, which you couldn't for much the same reason (if the compiler were on the same processor as the code.)Code:int myStrLen(const char *s)
{
if (!s[0])
return 0;
if (!s[1])
return 1;
...
if (!s[MAX_POINTER_VALUE])
return MAX_POINTER_VALUE;
}
Then there's this which doesn't actually work for two reasons:
Code:int myStrLen(const char *d)
{
return (int) d -
nextd:
(!d[0] ? d++, goto nextd : d);
}
It's also kind of sad that the const in "const char *s" stops you from doing any funny business using the buffer at s as a variable holder.
Actually, just let me ask... why ??? Why do you want to do this in the first place ? Or is this a riddle ?
And then there is the easiest solution...use 'strlen()'... :cool:Quote:
Originally posted by Gorgor
Then there's the solution that requires neither recursion nor two functions:
And then there is std::string...
Why bother with char * anymore? :)