macros - C++ How to reuse code blocks with multiple returns (exit points)? -
i have code block performs motion control procedure. basically, asks servo motor move position.
//code block starts err=setvelocity(vel); if(err!=0) return err_fail; err=setacceleration(acc); if(err!=0) return err_fail; err=setdeceleration(dec); if(err!=0) return err_fail; err=setposition(pos); if(err!=0) return err_fail; err=startmotion(); if(err!=0) return err_fail; //code block ends
and code block used, example, in homing procedure.
#define err_success 0 #define err_fail 1 short gohome(){ long vel,acc,dec,pos; short err; //move home //code block starts vel=vel1,acc=acc1,dec=dec1,pos=pos1; ... //code block ends //move offset //code block starts vel=vel2,acc=acc2,dec=dec2,pos=pos2; ... //code block ends return err_success; }
every time need "move to" procedure, have copy-paste code block modification on motion parameters. , actual code block larger 1 shown above, why don't know if it's idea define macro.
actually did define macro handle error.
#define iferrthenreturn(err){ \ cstring errinfo; \ if(err!=0){ \ switch(err){ \ case 0: errinfo = "command succeeded.\n"; break; \ case 1: errinfo = "command failed.\n"; break; \ case 2: errinfo = "unsupported license.\n"; break; \ case 3: errinfo = "parameter error.\n"; break; \ ... \ } \ afxmessagebox(errinfo); \ return em_err_fail; \ } \
so code block like
//code block starts err=setvelocity(vel); iferrthenreturn(err); ... //code block ends
but don't know it's wise define whole code block macro. tell me if there's other ways improve readability of higher level procedures "gohome" utilizes code block?
when writing code, important make nice , readable, in way future maintenance not have problems maintaining it. macros not provide way of keeping code readable, due macro call being replaced macro body itself, can lead misbehaviour unexpected results.
it easier have in function:
#define err_success 0 #define err_fail 1 bool relocate(long vel, lon acc, long dec, long pos) { int err=setvelocity(vel); if(err!=0) { return false; } err=setacceleration(acc); if(err!=0) { return false; } err=setdeceleration(dec); if(err!=0) { return false; } err=setposition(pos); if(err!=0) { return false; } err=startmotion(); if(err!=0) { return false; } return true; } short gohome() { //move home if(!relocate(vel1, acc1, dec1, pos1) { return err_fail; } //move offset if(!relocate(vel2, acc2, dec2, pos2) { return err_fail; } return err_success; }
this way there no need copy/paste code, have unneeded declarations of variables, , have function collects required functionality in 1 place
Comments
Post a Comment