ThePhD / future_cxx

Work done today for the glory of tomorrow - or, C and C++ systems programming papers.
https://thephd.dev/portfolio/standard
47 stars 8 forks source link

File scope resolution operator `::` in C #69

Closed frederick-vs-ja closed 1 year ago

frederick-vs-ja commented 1 year ago

Microsoft UCRT's type-generic macros are broken because they directly refer to C standard library functions with their names. E.g.

#define cbrt(X) _Generic((X), \
    long double: cbrtl,       \
    float:       cbrtf,       \
    default:     cbrt         \
)(X)

As a result, a locally declared function pointer can alternate the behavior of these macros, which is non-conforming (reported here, for sqrt and sqrtf).

#include <assert.h>
#include <tgmath.h>

int cbrt_like(float x) {
    return 42;
}

int main(void) {
    assert(cbrt(1.0f) == 1.0f); // OK.
    int (*cbrtf)(float) = cbrt_like;
    assert(cbrt(1.0f) == 1.0f); // This should also be OK, but fails.
}

A conforming implemention may need to use additional functions with _Ugly names (shown in N3096):

#define cbrt(X)                        \
    _Generic((X),                      \
        long double: _Roundwise_cbrtl, \
        default:     _Roundwise_cbrt,  \
        float:       _Roundwise_cbrtf  \
    )(X)

IMO this is adding unnecessary complexity. I believe the proper resolution is adding :: ("file scope resolution operator") to C, with which we can make macros more robust like this:

#define cbrt(X)               \
    _Generic((X),             \
        long double: ::cbrtl, \
        default:     ::cbrt,  \
        float:       ::cbrtf  \
    )(X)

Note that C++ namespaces can and perhaps should be avoided. :: should only make identifiers found in the file scope in C.

ThePhD commented 1 year ago

Sure. If you want to write that paper, you can and should write it. I don't really have the energy / bandwidth to do so, though. It looks like you already understand that this hints at potential C++ namespace stuff, so I'm sure you know to be careful if you write such a paper.