Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on Compile-time rounding with the pre-processor

Parent

Compile-time rounding with the pre-processor

+8
−0

When searching the Internet, I came across this SO post Rounding in C Preprocessor but immediately noted that none of the answers are showing a way to perform actual rounding - rather, they are doing flooring to the nearest integer.

The post is actually misleading and got nothing to do with rounding, but with getting the appropriate integer type back from the macro. Yet it is the #1 search engine hit when searching for rounding the the preprocessor, which is kind of sad.

Is there a way to round a floating point expression to an integer at compile-time, using the pre-processor?

I suppose such code could also either be written in a type-generic way accepting any of the common arithmetic types as input, or alternatively in a type safe manner only accepting one specific type as input. Is there an advantage in using one form or the other?

History

0 comment threads

Post
+6
−0

It doesn't really need to be carried out in the preprocessor as such, it is sufficient to realize that a constant expression in C, consisting only of constants ("literals") is always calculated at compile-time.

The actual math for doing rounding is then rather trivial. Example:

float some_float = 3.14f;
uint32_t result = some_float - (uint32_t)some_float > 0.5f ? 
                  (uint32_t) some_float+1 :
                  (uint32_t) some_float;

The compiler with optimizations enabled will just replace that with 3 at compile-time.

Turning that same code into a macro:

#define ROUND(flt)   ( (flt)-(uint32_t)flt > 0.5f ?     \
                       (uint32_t)flt+1 :                \
                       (uint32_t)flt )  

As long as flt is a constant expression, this will all get calculated at compile-time.


Regarding type safety:

The above macro would be type-generic, as in the macro will accept any arithmetic expression containing, float, double, int etc and return a uint32_t. The advantage/disadvantage is that a lot of constant expressions might not always have an obvious type due to implicit type promotion. For example something like true ? 1 : 0.0 always returns 1.0 and in a type that is double.

If we want to allow that or not depends on how stringent we are with types. In some hardware-restricted applications like microcontroller ones, there may not be a FPU present at all (very common) or there might be a FPU but only single-precision (Cortex M3 etc). In some cases, a target-aware IDE might decide to link in a big software floating-point lib just because it spotted the presence of a floating point type not supported by hardware, and that's generally a bad thing. Especially if we only wanted to do floating point as part of the preprocessor and keep all run-time calculations in fixed point, because we are using some low- to mid-range MCU.

Casting the expression back to an integer type may or may not mean that the IDE will not link in that software floating point lib. To avoid such situations in certain IDEs, then a type safe macro makes sense, to prevent that from happening by accident.

By taking some of the tricks from How to create meaningful error messages from _Generic macros?, such a type safe macro with meaningful compiler errors might look like this:

#define STATIC_ASSERT_EXPR(expr, msg) ( (void)(struct{ int dummy; static_assert(expr, msg); }){}.dummy )
#define IS_FLOAT(expr) _Generic((expr), float: true, default: false)

#define ROUNDF(flt) ( STATIC_ASSERT_EXPR(IS_FLOAT(flt), "Wrong argument " #flt " passed to ROUNDF, expected float.") \
                      , /* comma operator */           \
                      ((flt)-(uint32_t)flt > 0.5f ?    \
                      (uint32_t)flt+1 :                \
                      (uint32_t)flt )                  \
                    )

Complete example:

#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>

#define STATIC_ASSERT_EXPR(expr, msg) ( (void)(struct{ int dummy; static_assert(expr, msg); }){}.dummy )
#define IS_FLOAT(expr) _Generic((expr), float: true, default: false)

#define ROUNDF(flt) ( STATIC_ASSERT_EXPR(IS_FLOAT(flt), "Wrong argument " #flt " passed to ROUNDF, expected float.") \
                      , /* comma operator */           \
                      ((flt)-(uint32_t)flt > 0.5f ?    \
                      (uint32_t)flt+1 :                \
                      (uint32_t)flt )                  \
                    )

int main()
{
  printf("%"PRIu32 "\n", ROUNDF(3.14f));
  printf("%"PRIu32 "\n", ROUNDF(3.54f));
  printf("%"PRIu32 "\n", ROUNDF(3.14)); // compiler error
  printf("%"PRIu32 "\n", ROUNDF(3.54)); // compiler error
  printf("%"PRIu32 "\n", ROUNDF(3));    // compiler error
}
History

2 comment threads

Round half to even (1 comment)
Why can't you just add 0.5 before converting to integer? (2 comments)
Why can't you just add 0.5 before converting to integer?
Olin Lathrop‭ wrote 4 months ago

Why can't you just add 0.5 before converting to integer?

Lundin‭ wrote 4 months ago

Olin Lathrop‭ You could, it's essentially the same thing - it's all calculated at compile-time anyway. There's no difference between the relational (comparing) operators and the additive in terms of implicit promotions, except the former might in some cases be easier to evaluate since they always either result in 1 or 0. Pedantically there might be floating point inaccuracy to take in account too, but that's probably not an issue in most cases.