Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: How to name a struct field `errno`?

I want to define a struct:

struct error
{
    int errno;
    /* other information */
};

And then I want my code to have error paths that look like this:

struct error my_error;
my_error.errno = errno;
/* set other fields on the error */

But if the same translation unit includes #include <errno.h>, then errno is normally a macro which gets replaced with something else.

Assuming you actually need to access errno in that translation unit so you can't just undefine it, is there a way to still have that struct field name?

I don't care if it's by suppressing the expansion for a specific token, or by somehow getting the errno token to get generated by other macro expansions which don't then expand further, or whatever method.

Ultimately it doesn't matter and I can just name the field something else like error or error_number instead. I just don't like being unable to name things what seems to be the most appropriate name.

like image 860
mtraceur Avatar asked Oct 18 '25 12:10

mtraceur


1 Answers

Because you commented:

I want to achieve source code where stuff like this is possible ... because I think errno is self-evidently the most clear and optimal name for that field and it's offensive that C isn't letting me use the most appropriate name for something.

It's generally a bad idea to override common identifiers that are part of the language, because it confuses people. And, it will confuse yourself at some point, when you've forgotten you did this; so it's not even advisable in private own projects.

Writing meaningful bug free code is already a very demanding task for humans. Tricks like this make things more difficult to understand. Meaning matters the most in programming!

Then, I don't think that errno is such a great name that asks to be used elsewhere:

  • consists of two abbreviated parts: err and no.
  • doesn't use common camel-case errNo
  • good alternatives are easy/obvious (e.g. errorNumber)
  • in the example I see struct error, not struct err, so it seems you don't like the abbr. err that much

Finally, if errno is a macro, a line like: my_error.errno = errno;, which is at the heart of why you want this, will never be possible because the CPP won't be able to differentiate between the two errnos. QED.

like image 74
meaning-matters Avatar answered Oct 21 '25 01:10

meaning-matters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!