Battle-plan for CTFE

Stefam Koch via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Wed Oct 26 09:42:48 PDT 2016


On Wednesday, 26 October 2016 at 16:24:49 UTC, MakersF wrote:
> On Wednesday, 26 October 2016 at 15:02:28 UTC, Stefam Koch 
> wrote:
>> Who can guess what this code does ?
>>
>>
>> char[] obfuscatedFn(string a, string b, uint aLength = 0, uint 
>> bLength = 0, uint cLength = 0, uint pos = 0, uint bPos = 0, 
>> char[] result = [])
>> {
>>     aLength = cast(uint)a.length;
>>     bLength = cast(uint)a.length;
>>     cLength = aLength + bLength;
>>     result.length = cLength;
>>     while(aLength--)
>>     {
>>         result[pos] = a[pos];
>>         ++pos;
>>     }
>>     while(bLength--)
>>     {
>>         result[pos] = b[bPos++];
>>         ++pos;
>>     }
>>
>>     return result;
>> }
>
> Shouldn't
>> cLength = aLength + bLength;
>
> actually be
>> cLength = aLength + bLength + pos;
> ?
> Otherwise when pos is > 0 it writes past the end of result.
>
> Same problem in the first and second loop, where the legths 
> should probably be
>
>>     aLength = cast(uint)a.length - pos;
>>     bLength = cast(uint)a.length - bPos;
>
> If you fix the a and b Length then cLength is fine.
>
> Or am I missing something?

Ah the default paramters are never touched.
The reason they are there is because of the way the ctfe engine 
lowers parameters.
It's easier to create byte-code macros if all used variables are 
function paramters :)


More information about the Digitalmars-d-announce mailing list