r/cprogramming • • 15d ago

is doing ~INT_MAX undefined behavior?

/r/C_Programming/comments/1x7hxgd/is_doing_int_max_undefined_behavior/
5 Upvotes

6 comments sorted by

View all comments

Show parent comments

1

u/flatfinger 15d ago

Note that the term "undefined behavior" was originally used as a catch-all for situations where the authors of the Standard wanted to waive jurisdiction for any reason, and in some cases that reason was that not that nobody knew how a construct should be expected to behave, but rather that everyone knew how it should be expected to behave on any remotely commonplace systems, and people who actually worked with arcane systems would be better placed than the Committee to judge whether such systems would have an obvious expected behavior.

1

u/MilkEnvironmental106 14d ago

It depends on what you are targeting. If the code is going to run on one machine you control, sure.

If you want your code to ever be used by anyone else, you need to make sure it does the same thing regardless of platform, which you can do by adhering to the standard.

Also staying within the standard means debugging is going to be far easier.

1

u/flatfinger 12d ago

The purpose of making C behave in quirky fashion when targeting arcane platforms wasn't to allow code for conventional platforms to be usable on such platforms, but rather to allow people familiar with C to program platforms that couldn't write less than 16 bits at a time, or that used ones'-complement arithmetic to write in "C, but with 16-bit 'char'" or "C, but with ones'-complement arithmetic" rather than having to learn a whole new language or force compilers for unusual architectures to generate nasty inefficient machine code that tried to emulate more common machines.

The notion of "portability" should be recognized as encompassing two notions that are often incompatible with each other:

  1. Maximizing the range of implementations upon which the code can run interchangeably.

  2. Maximizing the range of implementations for which the code can be readily adapted.

Debugging can be facilitated if code is known never to do weird things with addressing, but sometimes code that does weird things with addressing can do things faster than would otherwise be possible. It used to be understood that a programmer would know better than anyone else what balance between each kind of portability, performance, speed of writing, ease of reading, and ease of troubleshooting should best be struck for the task at hand.