c - How could these case conversion functions be improved? -
as learning exercise, 3 functions—togglecase, lowercase , uppercase—each expect pointer ascii char string, terminated null character; work expected. there more efficient or faster methods of accomplishing task? breaking unspoken rules of c coding? i've made use of macros because, think, makes code better , more efficient function calls. typical or overkill?
please feel free nit-pick , critique code (but nice).
case_conversion.h
#define case_flag 32 #define a_z(c) (c >= 'a' && c <= 'z') #define a_z(c) (c >= 'a' && c <= 'z') void togglecase(char* c); void lowercase(char* c); void uppercase(char* c);
case_conversion.c
#include "case_conversion.h" void togglecase(char* c) { while (*c) { *c ^= a_z(*c) || a_z(*c) ? case_flag : 0; c++; } } void lowercase(char* c) { while (*c) { *c ^= a_z(*c) ? case_flag : 0; c++; } } void uppercase(char* c) { while (*c) { *c ^= a_z(*c) ? case_flag : 0; c++; } }
there @ least 2 major problems macros. consider happens if call 1 of them like
a_z('a' + 1);
the call not give correct results due operator precedence. easy fix using brackets:
#define a_z(c) ((c) >= 'a' && (c) <= 'z')
but can called this:
a_z(i++);
this call increment i
twice! , not fixable (if @ all) in macro. recommend using inline functions instead (if needed - see below).
the fastest way convert between upper/lowercase know of using lookup tables. of course, trades memory speed - pick preference knowing specific platform :-)
you need 2 arrays, 1 either direction. initialize them like
char toupper[128]; // care standard ascii (int = 0; < 128; i++) toupper[i] = i; toupper['a'] = 'a'; ... toupper['z'] = 'z';
and conversion trivial:
char touppercase(char c) { return toupper[c]; }
(for production code, should improved extend array possible char
values on given platform (or shrink legal values , parameter checking), illustration, do.)
Comments
Post a Comment