I'm working on a project on an 8051 where every byte counts. As such, I am using some global variables where I normally wouldn't. The normal method of passing pointers into a function adds too much overhead here.
I have a number of functions that use single bit variables (a compiler specific extension to C) to signal the outcome of a function in addition to the normal return value.
bit global_error_flag = 0;
bit global_data_ready_flag = 0;
unsigned char A_Function (void) {
// Do some stuff
if ( badness ) {
global_error_flag = 0;
global_data_ready_flag = 1;
return 0;
}
if ( data_is_ready_use ) {
global_data_ready_flag = 1;
}
return a_value;
}
void Other_Function (void) {
unsigned char c;
c = A_Function();
if( global_error_flag) {
// Do error stuff here.
}
else
if( global_data_ready_flag ) {
// Do data processing here.
}
global_error_flag = 0;
global_data_ready_flag = 0;
}
Given that the technique is evil, is there some way I can make the code clearer?
How best should I indicate which function calls will have the side-effect of setting these flags? Are comments enough? Should I name the functions to indicate their API (quasi-hungarian-style)? Should I use a macro to mark such calls:
#define FUNCTION_SETS_FLAGS(code) (code)
FUNCTION_SETS_FLAGS( c = A_Function() );
Any other ideas?
Using a convention, whether you want to call it "Hungarian" or not, is the best way I can think to mark this offhand. Stylistically, some sort of naming prefix would be preferable over the empty #define, at least to me.
This is actually pretty common, I think. I know that the S60 programming environment uses a lot of conventional tags on functions to indicate that they throw exceptions, for example.
Your globals are labelled for clarity, that's a good start.
Ideally you want something that won't compile if you get it wrong. That means macros and comments won't work.
I'd stick to a naming convention for the functions - not necessarily Hungarian, but something like A_Function_Returns_Flags
, or less verbose if you can think of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With