Making large constants in C source more readable?

只谈情不闲聊 提交于 2019-11-29 10:22:15

One possibility is to write it like that:

#define F_CPU (16 * 1000 * 1000)

alternatively

#define MHz (1000*1000)
#define F_CPU (16 * MHz)

Edit: The MHz(x) others suggested might be nicer

Yes, C does have preprocessor separators: ##

So you can write

#define F_CPU 16##000##000UL

which has exactly the same meaning as 16000000UL. (Unlike other structures like 16*1000*1000 where you need to be careful not to put them in places where the multiplication can cause problems.)

maybe something like that?

#define MHz(x) (1000000 * (x))
...
#define F_CPU MHz(16)

Also, I don't like #defines. Usually it's better to have enums or constants:

static const long MHz = 1000*1000;
static const long F_CPU = 16 * MHz;

You could write the constant as the result of a calculation (16*1000*1000 for your example). Even better, you could define another macro, MHZ(x), and define your constant as MHZ(16), which would make the code a little bit more self-documenting - at the expense of creating name-space collision probability.

// constants.h
#define Hz   1u              // 16 bits
#define kHz  (1000u  *  Hz)  // 16 bits
#define MHz  (1000ul * kHz)  // 32 bits

// somecode.h
#define F_CPU (16ul * MHz)   // 32 bits

Notes:

  • int is 16 bits on a 8 bit MCU.
  • 16 bit literals will get optimized down to 8 bit ones (with 8 bit instructions), whenever possible.
  • Signed integer literals are dangerous, particularly if mixed with bitwise operators, as common in embedded systems. Make everything unsigned by default.
  • Consider using a variable notation or comments that indicate that a constant is 32 bits, since 32 bit variables are very very slow on most 8-bitters.

You can use scientific notation:

#define F_CPU 1.6e+007

Or:

#define K 1000

#define F_CPU (1.6*K*K)

It might help readability to define the constant as:

#define F_CPU_HZ 16000000UL

That way you know what type of data is in it. In our SW we have a few peripherals which require assorted prescalers to be set, so we have a #defines like this:

#define SYS_CLK_MHZ    (48)
#define SYS_CLK_KHZ    (SYS_CLK_MHZ * 1000)
#define SYS_CLK_HZ     (SYS_CLK_KHZ * 1000)

Another aproach would be using the ## preprocessor operator in a more generic macro

#define NUM_GROUPED_4ARGS(a,b,c,d) (##a##b##c##d)
#define NUM_GROUPED_3ARGS(a,b,c)   (##a##b##c)

#define F_CPU NUM_GROUPED_3ARGS(16,000,000UL)

int num = NUM_GROUPED_4ARGS(-2,123,456,789); //int num = (-2123456789);
int fcpu = F_CPU; //int fcpu = (16000000UL);

This is somehow WYSIWYG but not immune against misuse. E. g. you might wnat the compiler to complain about

int num = NUM_GROUPED_4ARGS(-2,/123,456,789);  //int num = (-2/123456789); 

but it will not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!