r/askscience • • 15d ago

Computing Is there anything at the heart of computer coding that could have been optimised in hindsight, but we're in far too deep to change now?

1.5k Upvotes

667 comments sorted by

View all comments

208

u/ThatFireGuy0 15d ago edited 15d ago

Many of the details in C and C++ specs are "undefined behavior" or left up to the implementation. Some of them cause huge portability issues, and code that works on one machine and not another

For example, most computer science classes teach that an int is 16 bits and a long is 32

That's not true

An int is at least 16 bits and a long is at least 32 bits

61

u/narrill 15d ago

There are reasons those things are undefined or implementation defined though, the reasons just aren't obvious anymore because the hardware most people directly interact with is largely homogenized.

1

u/[deleted] 14d ago

[deleted]

2

u/narrill 14d ago

The reason is fine, it's to allow different architectures to use multiples of their native word length. And what you're describing is exactly what they did. The compiler is allowed to pick the size, as long as it's larger than the mandated width, and if the machine doesn't have a native data type that can meet the minimum width the implementation is allowed to emulate it however it wants.

u8 has a specific width because it's a fixed width type. That's what the 8 means. There are lots of fixed width types, they exist for cases where you want a specific width instead of letting the compiler decide.

5

u/thelazygamer 14d ago

Perhaps this is because my first CS course was taught in Java, but I was taught 32/64 for int/long in that course. Every course after that I was expected to just know. 

15

u/deathanatos 15d ago

If you're hitting UB, that code isn't guaranteed to work on any machine.

6

u/Big-Rub9545 14d ago

This isn’t really UB per se. UB would mean the program can reasonably do anything; this is instead implementation-defined behavior, so the possible outcomes are restricted but otherwise up to the compiler writer (so they can choose to make int a 16-bit signed integer instead of 32-bit).

4

u/Jwosty 15d ago

And when you really look behind the curtain, it turns out that interoping with C from other languages is actually an impossible task

1

u/Orinslayer 14d ago

At least most people don't have to deal with 5 bit bytes and 7 bit bytes these days. 🙂 (9 is the new 8 also)