Avoid Fill Char for Characters

Although the FillChar procedure was originally intended to be used for filling a string with the same character many times, it is also (even more commonly) used to fill a generic buffer with data. The most frequent use is probably zeroing a data structure, making it impossible to change the actual definition of the procedure (despite its name):

var rc: TRect; begi n

With strings changing to a character size of two bytes problems arise. The first is because the string is now twice as big, while the second parameter of FillChar is expressed in bytes, and not in number of logical characters. So the first of the two FillChar operations in this code snippet (from the CharTroubles example) fails, with the subsequent display operation showing a t: var strl, str2: string; begi n strl := 'here comes a string'; str2 := 'here comes a string';

FillChar (strl[l], Length (strl), 0); // nope! Memol.Lines.Add ( 'l5 char is: ' + strl[l5]);

FillChar (str2[l],

Length (str2) * StringElementSize (str2), 0); // yes! Memol.Lines.Add ( 'l5 char is: ' + str2[l5]);

What's even worse, though is that filling the string with zeros will do, but filling it with a specific character will cause a complete mess. In fact, if you fill the string with the letter A, for example:

FillChar (str2[1],

Length (str2) * StringElementSize (str2), 'A'); Memo1.Lines.Add ('15 char is: ' + str2[15]);

what you end up doing is not filling the string with the character $41 but with $4141, so the string will become a sequence of Chinese characters:

In other words, you should absolutely stop using FillChar for filling a string with copies of the same character and keep using the procedure only for data structures. For filling a string you can use StringOfChar instead:

I str2 := StringOfChar ('A', 15); Memo1.Lines.Add (str2);

If you need an AnsiString result, notice there is an overloaded version of StringOfChar, taking an AnsiChar character. Consider, though, that if you write: var

S: AnsiString; begi n

the compiler will use the WideChar version of StringOfChar and will convert the resulting UnicodeString to an AnsiString. To avoid the conversion you can write: S := StringOfChar(AnsiChar('A'), 15)

The simple reason is that the compiler cannot call an overloaded function based on the result type, but only based on input parameters.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment