r/cprogramming • • 5h ago

Why your C program loops forever when you type a letter, and how to read input safely

9 Upvotes

A question that comes up a lot: "I used scanf("%d", &x) and when I type abc my program spins forever."

Why it happens: when scanf can't parse the input as a number, it doesn't consume it. abc stays in the input buffer, the next scanf fails on the same characters, and so on forever.

The fix: check the return value (the number of items read successfully), and throw away the bad line when it fails:

c int age; printf("Enter your age: "); while (scanf("%d", &age) != 1) { int c; while ((c = getchar()) != '\n' && c != EOF) { } /* discard the bad input */ if (c == EOF) return 1; printf("That's not a number. Try again: "); }

A few other input traps worth knowing:

  • Strings with spaces: scanf("%s") stops at the first space. Use fgets(buf, sizeof buf, stdin), which also can't overflow the buffer.
  • fgets keeps the newline: strip it with buf[strcspn(buf, "\n")] = '\0';
  • Never use gets(): it was removed in C11 because it has no length limit.
  • Missing &: scanf("%d", age) passes a value where an address is expected, which is undefined behavior and usually a crash.

I wrote this up in more detail for beginners, with a worked example and a section on using the input with if/else (including the classic if (x = 5) bug): https://blog.emreguzel.ca/2026/09/29/user-input-in-c-a-complete-guide-for-beginners/


r/cprogramming • • 4h ago

Embedded C

3 Upvotes

Hi I'm interested in embedded C. Finished C language to Dynamic memory allocation. Don't know DSA yet. I think I should learn embedded C. From where should I start?


r/cprogramming • • 17h ago

I have an interview involving C whereas I typically use Python.

8 Upvotes

I have programmed in C before including on the job, but those experiences never really gets me ready for the wideness of interviews. I was wondering if there's a resource that exposes the things I take for granted in Python (within the standard library) and explains how it works in C.

edit: I just had my interview, thanks for the responses! I went over every link I got


r/cprogramming • • 6h ago

LibLayaX: run the Laya AI decision model inside your own app

Thumbnail
0 Upvotes

r/cprogramming • • 14h ago

How can I improve my thought process in C interviews instead of relying on memorized solutions?

Thumbnail
2 Upvotes

r/cprogramming • • 22h ago

Any recommendations for introduction material to using C++ for microcontrollers?

7 Upvotes

I have been programming Arduino & ESP32 for a while now using C++, but have never engaged with any formal introduction material. With AI/LLM generated content exploding among both major publishers and self-published authors, I am a bit wary to start buying books willy-nilly.

Anyone here that can give solid recommendations on introduction materials on C++ for microcontrollers (preferably that that they themselves have used and found worthwhile)?

I got one recommendation for "Embedded C" by Michael J. Pont (2002), but it is fairly old.


r/cprogramming • • 1d ago

How to use sigatomic_t volatile variables in signal handlers instead of calling several functions or making semops?

7 Upvotes

I'm sorry in advance if this isn't the space for this question, but I can't find much information on the subject. In my project I have a parent who forks several children and at one point, it will send SIGTERM to his still-alive kids. The kids, who are either working or "stuck" on a msgop. Immediately after receiving the signal, they get to... doing other things, including calling other functions and releasing or reserving sempahores, accessing a shared memory, doing other stuff based on whether they can make these semops. After these operations, the kids exit.

While my project still works like this, as it's a relatively small project, I'd like to code as correctly as possible and I read that signal handlers should be very short, preferably just few lines of code (like changing the sigatomic_t volatile variable's value). While it's my understanding that I'm supposed to check said variable's value somewhere in the code (and if it's changed, do everything I'm doing in the handler), I don't understand where I'm supposed to check its value because signals can interrupt the kids at any point in time.

Any sort of help, examples, explanations are extremely appreciated; I thank you in advance. Or even just someone pointing me to where I can find more examples, that specifically mention signal handlers and how my functions are supposed to be called immediately, that's also great.

(I can only use System V IPCs and none of my processes access the internet, in case it's relevant in any way)


r/cprogramming • • 1d ago

I'm creating a language that could replace C in low-level programming—want to join me?

0 Upvotes

I have been involved in low-level programming for a long time: I write operating systems and have created both a more user-friendly dialect of C and a programming language—designed for driver and firmware development—that can be learned in just a few hours. However, I am reaching out to you now because I cannot handle this task alone. Whether you know how to write low-level code, simply have an interest in the field, or possess a deep understanding of how such programs work, I invite you to join me in creating a programming language specifically designed for an operating system. Thank you for taking the time to read this message—the future is ours to shape.


r/cprogramming • • 2d ago

What are the good practices of managing small dependencies?

4 Upvotes

I'm new to C. I have a small SDL2 project. At some point I needed to load and draw image sprites and found nice library stb_image.h. Probably best way here would be to just download the stb_image.h file and commit it to the repo, but I thought it would be a nice exercise towards learning how to manage dependencies. Since C doesn't seem to have anything like cargo, PyPi or npm, I started to look for best practices on how to do that.

So, this is what I came up with so far, with a Makefile:

  • dependency file as a target, with commit pinned as separate var

```make STB_IMAGE_COMMIT := 013ac3beddff3dbffafd5177e7972067cd2b5083

vendor/stb/stb_image.h: curl -fsSL --create-dirs https://raw.githubusercontent.com/nothings/stb/$(STB_IMAGE_COMMIT)/stb_image.h -o $@ ```

  • making it prerequisite to the main build target:

make build/%.o: src/%.c | build vendor/stb/stb_image.h $(CC) $(CFLAGS) -c $< -o $@

This seems simple, reproducible and efficient to me. But I'm not sure it would scale well and also - maybe there are better approaches out there?


r/cprogramming • • 3d ago

Help with learning C

23 Upvotes

Hello, so ive been trying to learn C, im in love with programming, i loved tech ever since i was young, but i just didnt have quite the intelligence for programming.
and now, well i grew up and i can understand and actually learn things faster, i started learning many languages since i wasnt sure which language to pick, i learned some of python, c++, c#, and some others one.

but now, i really like C, because i love lower level stuff, and i can learn how the computer works etc, i used the Beej’s Guide to C Programming website, it pretty good, i learned so much about c, i stoped at chapter 9 (*FILE).
because i realised that i learn by making stuff, but not looking at stuff, i dont know what to make or anything, and im stuck im not learning anything else.

i would really love some tips, sorry if i made this long, i tried providing details.


r/cprogramming • • 3d ago

Flint v0.5.5 — C/C++ projects no longer need manual source/header lists

Thumbnail
github.com
10 Upvotes

I've been working on Flint, an open-source build system + package manager for C/C++, and v0.5.5 removes one of the things that has always bothered me about configuring C/C++ projects: having to tell the build system where every source/header directory lives.

Then your build configuration needs to keep track of which directories contain sources, which are headers, which libraries to link, which files to exclude, etc.

With v0.5.5, Flint can discover project resources automatically.

You can organize your project normally, and Flint figures out the files that need to be involved in the build.

What's new in v0.5.5

  • Automatic resource discovery

You no longer need to manually configure:

  • src

  • include_paths

  • static

  • shared

Flint discovers the relevant resources in the project automatically.

  • Smarter exclusions

You can now control discovery with:

```text

  • excludes

  • exclude_dirs

  • exclude_exception

```

This makes it possible to ignore things like platform-specific implementations, experimental code, generated files, or legacy directories without writing custom build logic.

  • Native .h.in templates

Flint can now generate headers from .h.in templates with variable substitution.

For example, this makes generated version headers possible without requiring an external configuration tool.

  • Standardized project macros

Project-generated macros have been standardized around:

```c

PROJECT_VERSION

```

to reduce the possibility of collisions with third-party libraries.

  • More CLI functionality

v0.5.5 also adds:

```bash

flint help

flint version

flint deps

flint cache

```

for CLI help, version information, and dependency/build-cache management.

The resulting project configuration

A small C project can now look roughly like this:

```json

{

"project_name": "example_project",

"project_language": "c",

"version": "0.1.0",

"compiler_path": "/usr/bin/gcc",

"executable": true,

"flags": ["-Wall", "-O2"],

"dependencies": {

"example_lib": {

"version": "1.0.0",

"remote": "https://github.com/user/example_lib.git"

}

}

}

```

Then:

```bash

flint build

```

handles source/header discovery, dependency handling, linking, and compilation.

The broader idea behind Flint is pretty simple: I want C/C++ project configuration to describe what a project is, rather than manually describing how every file should be built.

I'm still actively working on it, so I'm particularly interested in feedback from people who maintain C/C++ projects.

What part of your current C/C++ build setup do you find the most annoying?

And if you want to take a look at the implementation:

GitHub: https://github.com/mainak55512/flint

If you find the approach useful, a GitHub star is appreciated — but I'm especially interested in hearing where this approach breaks down or what you'd change.


r/cprogramming • • 3d ago

what is the best book for learning c

13 Upvotes

r/cprogramming • • 3d ago

Glibc posix 2024 incompatibility

5 Upvotes

I been coding some posix porable stuff and i tried to use pipe2 and dup3 which are considerd posix since 2024 (Issue 8) i defined _POSIX_C_SOURCE to 202405L and included unistd.h and gcc greated me with implicit declaration i looked at my local unistd.h and it had pipe2 and dup3 behind __USE_GNU which is just wrong so i checked offical source code latest branch and it had the same bug, Please if some of you guys have sourceware bugzilla account please report it, it is a big issue


r/cprogramming • • 4d ago

Learning C and looking for project ideas

26 Upvotes

I’m currently learning C using "C Programming: A Modern Approach" book along with a youtube playlist. I’m doing the exercises from the book, but I’d also like to build some small applications to get more hands-on practice.I have experience with full-stack web development, so I can build relatively large web applications, but C feels like a completely different world and I’m not really sure what would be good to build as a beginner.What kind of small projects would you recommend for practicing C? Also, are there any good places or resources where I can find project ideas or exercises?


r/cprogramming • • 5d ago

Where should I practice C programming?

23 Upvotes

My first-semester course includes C programming and I’ve already learned the basics through videos and other resources on the internet, but I’m not really sure where or how I should practice it properly.

Should I use platforms like LeetCode, HackerRank, CodeChef, etc., or are there better websites/resources specifically for learning and practicing C from the basics? I’d also appreciate suggestions on what kind of problems I should start with and how I should progress from there.


r/cprogramming • • 5d ago

Tech questions

Thumbnail
0 Upvotes

Are “ <> “ , angle brackets,used by programmers , to insert code, commands, or anything else if there’s content between them?
Example:
< my name>
Now, these brackets , in the “behind -the -scenes “, situation, have a specific purpose/meaning for the computer to assess and then implement/ follow. This is what I’m told so I need clarification!!


r/cprogramming • • 6d ago

I spent 7 years building a game engine using C

134 Upvotes

I've been working on a puzzle game for the last 7 years, and over time I ended up writing almost the entire technology stack myself.

The code is written in a C style, using a C++ compiler mainly because I like operator overloading for math. Other than that, I try to keep the code close to how I would write C. I don't use the standard library, exceptions, RTTI, RAII or object-oriented abstractions.

I made my own build system, UI library, in-game editor, Vulkan renderer, asset pipeline and most of the other tools I use to make the game.

There is no SDL or Dear ImGui. Most of the code is my own, along with a few small libraries such as stb_truetype and miniaudio.

I really like having direct control over all these parts of the codebase. If the game needs something new, I can change the renderer, tools, asset pipeline, build system or engine directly instead of working around an existing framework.

The game is a rule-discovery puzzle game, and building the technology behind it has been just as interesting to me as making the game itself.

The demo is now available on Steam if you want to see what I ended up making:

https://store.steampowered.com/app/5017320/Satelital_Demo/

The full game is planned for release later this year in November.

I'd be interested to hear how other people structure larger C projects, especially around memory management, build systems, UI and tools. I'm always interested in seeing how other people approach these problems.


r/cprogramming • • 5d ago

Tech questions

Thumbnail
0 Upvotes

Are “ <> “ ( angle brackets ) those used by programmers to insert code to whatever is inserted between these?
Not necessarily cool but programmers use this for directives and command structures and so on, so I’m told is that accurate?


r/cprogramming • • 7d ago

native rdf triplestore written in C

14 Upvotes

I wanna share with you the current project i am working on, its a triplestore written in c, its still on early stage, already implemented data storage, and ttl file parsing and loading, with a simple sparql query parser.

link : https://github.com/vrtkarim/native-rdf-triplestore

Feel free to contribute! Feedback, ideas, issues, and pull requests are welcome.


r/cprogramming • • 7d ago

Confused about strings seemingly resetting after future inputs.

Thumbnail
1 Upvotes

r/cprogramming • • 9d ago

How can I learn C from absolute zero?I don't understand programming logic at all.

Thumbnail
0 Upvotes

r/cprogramming • • 10d ago

For command working weirdly

4 Upvotes

Edit: Declaring n as 1 and changing the for loop to (i = n-1; i > 0; --i) as was suggested seems to have worked. Still don't really get the logic behind it, neither why the order inside the for expression was affecting the result nor why changing the n to 1 from 0 and i to n - 1 made a difference. Aren't they the same value at the end? Anyway, thanks.

For some reason, my "for" command only works when I put the increment in the middle and the condition at the end. I have no clue what's going on but the code is working fine when I do this.

I'm using devc++, the rest of the code is me declaring global variables and asking the user for inputs to fill the arrays. Everything is working exactly as intended but breaks if I write the "for" the regular way.

for(i = n; i--; i>0){

        printf("Codigo: %d", codigo\[i\]);

        printf("\\nProduto: %s", nome\[i\]);

        printf("\\nPeso: %.2f", peso\[i\]);

        printf("\\nPreco: %.2f", preco\[i\]);

        if(regiao\[i\]==1){

printf("\nRegiao: Sudeste");

        }

        else if(regiao\[i\]==2){

printf("\nRegiao: Sul");

        }

        else if(regiao\[i\]==3){

printf("\nRegiao: Nordeste");

        }

        else if(regiao\[i\]==4){

printf("\nRegiao: Norte");

        }

        printf("\\n\\n");

r/cprogramming • • 11d ago

I have 4dumb questions about C

54 Upvotes
  1. I have read the "C bible" (k &R book) and admittedly understood about 80 to 85 percent of it and did almost all of its exercises without AI , not all but very few were undone, why do I feel like idk Jack shit about C? I have coded projects and I'm not "beginner" but it still feels like idk anything about how to make it productive

  2. What are the most essential parts you'd think someone learning should focus on? I'm not saying basic stuff like the syntax , I'm talking about building stuff

  3. Why the hell is it so hard to read opensource code? Admittedly I am new to that one, but I can't even fathom contributing to open source when I look at the code it feels like I'm reading Chinese... the hell am I supposed to do?

  4. Are there even any actual job markets related to C besides embedded? Don't get me wrong I really enjoy the language and do like to work with it as a hobby but I'm a mid 20 adult and need a good job sooner sooo... kinda need yo focus on more important stuff than just hobbies

Edit: sorry I forgot to say hi, thanks for reading

Edit2:

For the people who say I should build stuff, I understand and appreciate your advice but I should have mentioned I have done some stuff like that I'll reference a couple things I built

  1. Text editor in the terminal
  2. Http server with semi advanced way of handling requests
  3. Shell and basic mallow
  4. Dumb I know but hash maps in c just to practice
  5. Basic database (admittedly I got too busy with other things and didn't finish it fully)

r/cprogramming • • 11d ago

Building real world C Project

15 Upvotes

How can I go from building self projects to actual real world C Project how to bridge the gap between it and looking at C project on GitHub feels like completely new language that I don't understand .I am at intermediate level in C

Ik this is a dumb question but any guide will be helpful


r/cprogramming • • 11d ago

Making portable my unportable transputer C compiler

Thumbnail
nanochess.org
4 Upvotes