Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

embedded - Making large constants in C source more readable?

I'm working on some code for a microprocessor.
It has a few large, critical constants.

#define F_CPU 16000000UL

In this case, this is the CPU frequency. In Hertz.

As it is, it's rather hard to tell if that's 1,600,000, 160,000,000 or 16,000,000 without manually tabbing a cursor across the digits.

If I put commas in the number #define F_CPU 16,000,000UL, it truncates the constant.

I've worked with a few esoteric languages that have a specific digit-separator character, intended to make large numbers more readable (ex 16_000_000, mostly in languages intended for MCUs). Large "magic numbers" are rather common in embedded stuff, as they are needed to describe aspects of how a MCU talks to the real world.

Is there anything like this in C?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...