In C, I have a function that implements both the encryption and decryption routines of a block cipher. In order to both maintain a common naming and use convention, and to leave open the possibility of separating the routines into two different functions later, I’ve done the following:
void cipher(char *out, const char *in);
#define encrypt cipher
#define decrypt cipher
That works fine, except that I’d really like to hide the actual function (cipher) so people have to use encrypt or decrypt. Right now, cipher is part of the public interface, so if I decide to separate it into two different functions later and delete cipher, strictly speaking, I’m breaking the interface. But if I can hide cipher so only encrypt and decrypt are part of the interface, I’ll be fine.
The only option I’ve come up with so far is make cipher static, and implement actual functions for encrypt an decrypt to call cipher, but I’m not sure that the added overhead is actually worth it (I’m trying to keep the code size as tight as possible, and I have multiple occurrences of this same problem).
Is there something I can do with function pointers? Any other ideas?
You could use function pointers:
At least in typical use (the user just uses
encrypt(whatever);) this wouldn’t normally be visible. The only obvious problem would be that as defined above, the pointers remain writable, so you might want to make themconstso the user can’t accidentally overwrite them with the address of some other function.Another possibility would be to live with the name
cipherbeing public (or rename it to something likeprivate_cipher_to avoid accidental name collisions) and then just use a couple of macros:This should ensure against any overhead.