offsetof-style Fun with Ternary Conditional

S

Shao Miller

A possibly interesting/curious use of the ternary conditional
operator...

The only thing I could find to do with it was the non-portable:

#include <stddef.h>

#define NULL_OF_TYPE(x) \
(1 ? 0 : &(x))
#define offsetof2(id, member) \
((size_t)&(NULL_OF_TYPE(id)->member))

int main(void) {
struct {
double bar;
long baz;
} foo;

return (int)offsetof2(foo, baz);
}

This 'offsetof2' macro doesn't take 'struct XXX' as its first
argument, but an actual lvalue of a struct type.

A fellow C programmer had suggested a look here[1][*], which is pretty
loose inspiration.

Enjoy (for what it's worth).

- Shao Miller

[1] http://www.artima.com/cppsource/foreach.html
[*] It's C++
 
B

Barry Schwarz

A possibly interesting/curious use of the ternary conditional
operator...

The only thing I could find to do with it was the non-portable:

#include <stddef.h>

#define NULL_OF_TYPE(x) \
(1 ? 0 : &(x))

An expression which will always evaluate to (cast to pointer to type
of x)0.
#define offsetof2(id, member) \
((size_t)&(NULL_OF_TYPE(id)->member))

int main(void) {
struct {
double bar;
long baz;
} foo;

return (int)offsetof2(foo, baz);
}

This 'offsetof2' macro doesn't take 'struct XXX' as its first
argument, but an actual lvalue of a struct type.

A fellow C programmer had suggested a look here[1][*], which is pretty
loose inspiration.

Why not just look at 6.5.15-6 which is what forces the desired
behavior?
 
S

Shao Miller

Why not just look at 6.5.15-6 which is what forces the desired
behavior?
Sorry, Barry... That's exactly what the 'NULL_OF_TYPE' macro is...
From the section you've referenced. I'm not sure I understand. :(
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top