c - Logic of #define (microchip xc8 compiler) -


i started learning c pic programming , looking @ other people's code , @ includes files provided compiler, fundamental ones (xc.h, pic.h, pic specific headers...) , saw construct (it's found in pic.h)

#define __delay_us(x) _delay((unsigned long)((x)*(_xtal_freq/4000000.0))) 

naturally works, have problems understanding underlying logic of it. understand #define "alias maker", tell compiler substitute code x y every time it's encountered in program. that's it, simple substitution. here see variable, input or argument (x), passed substitute don't how! if me have made function this, , see how useful construct can be, if find code delay macro unnecessarily made (maybe because author didn't know native _delay, or because i'm porting code form compiler) can redefine (hypothetical!) "wait(200)" point native "_delay(200)". question can explain me how construct works? x not declared, wouldn't treated simple character substitute , not value passed? construct equivalent?

#define wait(x) __delay_us(unsigned long x) 

__delay_us(x) here function-like macro. function-like macros allow more dynamic constants (nice paradox, eh). works normal macro, give them argument. argument substituted literally macro substituted code. example:

float y = 12000000.0; unsigned long delay = __delay_us(y); 

will expaned to:

float y = 12000000.0; unsigned long delay = _delay((unsigned long)((y)*(_xtal_freq/4000000.0))); 

(note y instead of x)

be careful when defining own function-like macros:

  1. the arguments substituted literally, make sure occur once in macro-body. if provides function-call argument give unwanted results.
  2. as you've seen, no type-checking done @ all, types don't exist in macros.

for more pitfalls: http://gcc.gnu.org/onlinedocs/cpp/macro-pitfalls.html (although you're not using gcc, still applies)


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -