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 account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

September 2024

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

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jul. 4th, 2025 03:34 pm
Powered by Dreamwidth Studios