Tuesday, July 8, 2008

Discuss StrToUpper code

Discuss the following code:
/*
* Converts an lower case letter into an upper case letter.
* If the letter is not lower case, it does nothing.
* In ASCII, upper case letters come before lower case
* letters ('A' is 65, 'a' is 97) so we need to subtract
* to convert.
*/
#define MAKE_UPPER_CASE(c) \
(((c > 'a') && (c < 'z')) ? (c - ('a' - 'A')) : c)

/*
* StrToUpper -
* Converts a string to be in all upper case. Returns a pointer
* to the new, null-terminated, all-upper-case string.
*/
char *StrToUpper(const char* str)
{
char upperCaseString[1000];
int i = 0;

while (i < strlen(str)) {
upperCaseString[i] = MAKE_UPPER_CASE(str[i++]);
}

return upperCaseString;
}

Macro
  • Does not evaluate expressions before passing to macro. Thus, i++ will get executed for each appearance of c in MAKE_UPPER_CASE.

  • Better to use inline function for type-checking

  • (c - ('a' - 'A')) could be replaced by c + 32 for performance

  • c > 'a' and c < 'z' should be that and equal to
Function
  • Uses local storage: May be garbage because program may overwrite later on. Should either dynamically allocate return string or have input a string buffer as a parameter.

  • Does not append '\0' (null) character

  • upperCaseString[1000] can only contain 1000 chars and a large input str will cause buffer overflow.

  • int i may overflow if str is large

  • strlen() can be pulled out of the while statement so it won't be executed each time through the loop

No comments: