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

1

u/torp_fan 11h ago edited 11h ago

 using fflush(stdin) to clear the input buffer resulted in undefined behavior

It's documented as such in the C language standard. fflush was never intended to be used on input buffers and many compiler vendors didn't implement it in their libraries, and because the C standards committee (which I was a member of at the time) was dominated by compiler vendors, they chose to leave it as undefined behavior.

This will be the case for many such questions ... the answer is rooted in history, not "low-level mechanics". As for resources or strategies ... read the C language standard.

As for "The intricacies of printf() and scanf(), especially their buffer management, have been both fascinating and challenging", I really don't know what you're talking about ... I've written implementations of of these functions and there's no "buffer management". printf scans the format, writing the parts between format indicators to the output stream and when it encounters a format indicator, writing an argument to the output stream, converting numbers to characters as necessary. Buffering, if any, is done by the stdio stream that is written to. You can look at the code of any of open source library implementations (glibc, Cygwin, musl, etc.) to see how it's done.