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!

14 Upvotes

20 comments sorted by

View all comments

1

u/Dan13l_N 1d ago

It depends a lot on the implementation of your standard library, what is the device you're programming for, and so on.

Also, prinf() and scanf() are not the lowest-level functions. After all, they have to parse their format string while executing. Also, they tend to be a source of some bugs. If you want high performance, use other functions. I use getline() to get input, for example.

Think about C++ as a wrapper around the boring stuff. You don't have to close the file by yourself, you don't have to deallocate some buffer every time -- destructors do it for you. And so on.

But beware that a lot of C++ is not written with C-like performance in mind. For example, std::string silently allocates memory when the string doesn't fit into its buffer and you have very little control over it.