Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Disable type-limits check for a macro

I'm trying to build a simple SIGNOF macro:

#define SIGNOF(a) ((a) < 0 ? -1 : 1)

If a is negative it should return -1, otherwise 1. If a is an unsigned type, it should always return 1 and the compiler can optimize away the negative code path.

However, GCC rightfully warns me that

error: comparison of unsigned expression in ‘< 0’ is always false [-Werror=type-limits]
   29 | #define SIGNOF(a) ((a) < 0 ? -1 : 1)

But in this case I actually want this behavior. Is there any way to tell the compiler that this is intentional, similar to /* fall-though */ in a switch-case?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

If your compiler supports it, you can use _Generic:

#define SIGNOF(a) _Generic(a, unsigned char: 1,          \
                              unsigned short: 1,         \
                              unsigned int: 1,           \
                              unsigned long: 1,          \
                              unsigned long long: 1,     \
                              default: (a) < 0 ? -1 : 1)
over 4 years ago · Santiago Trujillo Report

0

What works is

static inline int __signof(long long a)
{
    return a < 0 ? -1 : 1;
}

#define SIGNOF(a) _Generic(a, unsigned char: 1,          \
                              unsigned short: 1,         \
                              unsigned int: 1,           \
                              unsigned long: 1,          \
                              unsigned long long: 1,     \
                              default: __signof(a))
over 4 years ago · Santiago Trujillo Report

0

This seems to fix the warning problem, at the expense of evaluating the operand twice:

#define SIGNOF(a) ((a) == 0 ? +1 : ((a) > 0) ? +1 : -1)

I observe that since the proposed DIV_ROUND() macro evaluates both its arguments twice, it also has problems if the arguments have side effects (increments, function calls, etc).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!