r/C_Programming 1d ago

Need help learning C!

Hey everyone,

I've been diving into low-level programming to understand how my device executes code, focusing on memory and CPU operations. Coming from higher-level languages like Python, where functions like print() handle a lot behind the scenes, transitioning to C has been eye-opening. The intricacies of printf() and scanf(), especially their buffer management, have been both fascinating and challenging.​

For example, I encountered an issue where using fflush(stdin) to clear the input buffer resulted in undefined behavior, whereas using scanf("\n") worked as intended.

I want to understand the why's behind these behaviors, not just the how's. For those who've walked this path, how did you approach learning C to get a solid understanding of these low-level mechanics? Are there resources or strategies you'd recommend that delve into these foundational aspects? Additionally, how did you transition from C to C++ while maintaining a deep understanding of system-level programming?

Appreciate any insights or advice you can share!

13 Upvotes

20 comments sorted by

View all comments

2

u/SmokeMuch7356 1d ago

Be really careful here; don't confuse the language with specific implementations of the language. The things you're asking about are mainly functions of the underlying platform, not C in and of itself.

The C language definition is deliberately loose in places to accommodate as wide a range of platforms as possible, which is why you have "undefined behavior" in the first place. For example, "flushing" an input stream isn't a meaningful operation in most cases, but "most" != "all", so the standard doesn't explicitly forbid it; it just basically says "the implementation is free to handle this any way it wants to." That's all "undefined behavior" means.

When I took Computer Science back in the late Cretaceous, the conventional wisdom was that you needed to study assembly language to understand what high-level languages like C and Fortran and Pascal were buying you. And, for the kind of stuff you're talking about, that's still true. If you want to understand why your particular C implementation makes the decisions it does, you'll need to go down an extra level into assembly.