dtm: (Default)
[personal profile] dtm

In C, and in C++ code written by people who still think they're writing C (and, in their defense, most of this code dates from before wide adoption of the STL and before ISO-standard C++ compilers were commonplace), a common pattern for functions which output strings (or other arrays) is to pass in an array and the length of the array as parameters to the function, and expect this array to be filled in by the function. For example:

int FameDate::GetDateAsString(char * output, unsigned int MaxStringLen)

So far, so good. The antipattern comes in when a default value is declared for MaxStringLen, especially one that is much larger than programmers might ordinarily expect. This leads to people doing:

char datestr[20];
myDate.GetDateAsString(datestr);


even though the default value for MaxStringLen might be 40 or more. The consequences are left as an exercise for the reader.

I'm trying to boil this antipattern down to a simple rule, and the best I've got is this: An array and its length are one logical object - it should never be possible to pass in only the array without its length. This has the advantage of pointing out that things like sprintf and strcpy are fundamentally prone to error, but we knew that. It has the disadvantage of being a rather clumsy statement.

This is not really clumsy.

Date: 2004-04-07 09:57 pm (UTC)
From: (Anonymous)
After all, in Pascal, an array and its length *are* one object. Same for strings and their length. They 'got it right', so to speak.

C strings, by not including a length, were fundamentally misdesigned, which is kind of horrible, really, and probably the single best reason never to use C. :-P (Note that, since you have to carry lengths everywhere anyway in properly written programs, zero-termination is close to being a waste of space; but we appear to be stuck with such silliness due to this fundamental design flaw.)

September 2024

S M T W T F S
1234567
891011121314
15161718192021
22232425 262728
2930     

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 23rd, 2025 03:19 am
Powered by Dreamwidth Studios