r/C_Programming Feb 23 '24

Latest working draft N3220

Upvotes

https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf

Update y'all's bookmarks if you're still referring to N3096!

C23 is done, and there are no more public drafts: it will only be available for purchase. However, although this is teeeeechnically therefore a draft of whatever the next Standard C2Y ends up being, this "draft" contains no changes from C23 except to remove the 2023 branding and add a bullet at the beginning about all the C2Y content that ... doesn't exist yet.

Since over 500 edits (some small, many large, some quite sweeping) were applied to C23 after the final draft N3096 was released, this is in practice as close as you will get to a free edition of C23.

So this one is the number for the community to remember, and the de-facto successor to old beloved N1570.

Happy coding! 💜


r/C_Programming 5d ago

Learning C weekly megapost for 2026-09-02

Upvotes

If you have questions about how to learn C:

  • which books are best?
  • which videos are best?
  • which classes are best?
  • which websites are best?
  • is there a "roadmap"?
  • what projects can I do?

then this is the thread for you. Add your question here. Do not make a stand-alone post, as it will be removed.

Remember that our sub has a very useful wiki that has a great list of resources for learning C programming.


r/C_Programming 1h ago

What else do I need to read on Arena Allocators?

Thumbnail gingerbill.org
Upvotes

(I realized the title of this post a bit misleading, as I also want code examples in comments if its possible. I want to know how the backing buffer is actually used when you have 10 "objects" in need of it)

Im currently taking a course in 42KL (extremely mixed personal opinion about the whole structure/syllabus). in the side, I decided to learn some extras.

Im having trouble looking for the code that actually uses the backing buffer allocated here in this sites code examples.

They say with Arena Allocators, you can have allocate 100s or even more particles/etc, with minimal fuss or (programmers) overhead thinking about freeing everytime you allocate memory for something.

Another article even quotes, something like your scoping issue is solved with custom allocators like these.

If you want to know the purpose, Im simply learning something different, becoz I dont like the idea of a syllabus shaping how a programmer thinks of a programming language (or programming in general)

(Im sorry if I sound like Im absolutely trashing all the terminologies, Im not a C specialist, or a big C fan for that matter, Im quite neutral to C)


r/C_Programming 2h ago

Question How can printf() change unrelated uninitialized variable behavior?

Upvotes

So, I just fixed a strange bug. I have a loop that loops through a char array until it finds a null terminator.I had miswritten and overlooked this after deleting a second variable I was initializing in that loop. So I ended up with:

for (int i; text[i] != '\0'; i++){}

Which I have since fixed. However, curiously, this program was running with normal operation because of a printf() statement operating on completely unrelated data; i would initialize to 0 every time. Other assignments happened between this print and the errored line as well.

printf("ID: %u\n", tID);

It had to be placed at a specific spot for it to fix the bug, but it fixed it every time, so the bug went unnoticed until I was cleaning up.

But, how exactly would this happen? What does printf() do that would change initialized variable behavior, and why was it consistently initializing to 0?

The value of i would print to 21937 without the printf() and 0 with it.


r/C_Programming 18h ago

recursive descent with coroutines

Thumbnail napcakes.nekoweb.org
Upvotes

r/C_Programming 1d ago

Question Advantages of Anonymous structs?

Upvotes

When are anonymous structs useful? What the advantages of one vs a non anonymous one?


r/C_Programming 1d ago

Wayland tutorial for beginners in pure C

Thumbnail
youtube.com
Upvotes

r/C_Programming 20h ago

Undocumented Behaviour in WinSock API?

Upvotes

I have two code examples of simple WinSock programs that listen for connections using an Event object associated with a listening socket. Before reading further, check these two code snippets and guess (without running them) what you think will happen in both.

Code snippet 1:

int main() {
  WSADATA wsaData;
  int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
  // ... error handling omitted

  int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  // ... error handling omitted

  // Make the socket non-blocking
  u_long mode = 1;
  res = ioctlsocket(sock, FIONBIO, &mode);
  // ... error handling omitted

  // Bind the socket to a specific address and port
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = INADDR_ANY;
  addr.sin_port = htons(7878);

  if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
    // ... error handling omitted
  }

  // Listen for incoming connections
  if (listen(sock, 10) == SOCKET_ERROR) {
    // ... error handling omitted
  }

  // Wait for incoming connections
  // Create a WSAEVENT object
  WSAEVENT event = WSACreateEvent();
  // ... error handling omitted

  // Associate the WSAEVENT object with the socket
  res = WSAEventSelect(sock, event, FD_ACCEPT);
  // ... error handling omitted

  // Wait for an event on the socket
  res = WaitForMultipleObjects(1, &event, FALSE, INFINITE);
  // ... error handling omitted

  /**
   * Closing the event object here before using the socket and without
   * disassociating it with the socket
   */
  WSACloseEvent(event);

  int conn_sock = accept(sock, NULL, NULL);
  // ... error handling omitted

  printf("New connection\n");

  closesocket(conn_sock);
  printf("Connection closed\n");

  closesocket(sock);
  WSACleanup();

  return 0;
}

Code snippet 2:

int main() {
  WSADATA wsaData;
  int res = WSAStartup(MAKEWORD(2, 2), &wsaData);
  // ... error handling omitted

  int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  // ... error handling omitted

  // Make the socket non-blocking
  u_long mode = 1;
  res = ioctlsocket(sock, FIONBIO, &mode);
  // ... error handling omitted

  // Bind the socket to a specific address and port
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = INADDR_ANY;
  addr.sin_port = htons(7878);

  if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
    // ... error handling omitted
  }

  // Listen for incoming connections
  if (listen(sock, 10) == SOCKET_ERROR) {
    // ... error handling omitted
  }

  // Wait for incoming connections
  // Create a WSAEVENT object
  WSAEVENT event = WSACreateEvent();
  // ... error handling omitted

  // Associate the WSAEVENT object with the socket
  res = WSAEventSelect(sock, event, FD_ACCEPT);
  // ... error handling omitted

  // Wait for an event on the socket
  res = WaitForMultipleObjects(1, &event, FALSE, INFINITE);
  // ... error handling omitted

  /**
   * Closing the event object after disassociating it from the socket, but
   * before using the socket
   */
  res = WSAEventSelect(sock, event, 0);
  WSACloseEvent(event);

  int conn_sock = accept(sock, NULL, NULL);
  if (conn_sock == INVALID_SOCKET) {
    printf("accept failed with error: %d\n", WSAGetLastError());
    closesocket(sock);
    WSACleanup();
    return 1;
  }

  printf("New connection\n");

  closesocket(conn_sock);
  printf("Connection closed\n");

  closesocket(sock);
  WSACleanup();

  return 0;
}

If you had guessed that the first snippet would crash, you would be right. Apparently, if you associate an event object with a socket, closing the event object will lead to operations on the socket returning WSAENOTSOCK error. If you dissociate the event object from the socket first, you can use it without problems.

I can't find any references in the documentation to this behaviour (I checked the WSAEventSelect and WSACloseEvent documentation). I know it may seem simple, but I discovered this in a more complex codebase where reproducing and tracing it was much more difficult.

Did you know this? Are there any more quirks related to the relationship between EventObjects and Sockets?


r/C_Programming 12h ago

Im making an OS what should i add

Upvotes

Hey everyone,

I’ve been thinking about making my own operating system for a LONG time, and I finally started building it.

I’ve actually been working on Souwede OS for around 11 months now, and it’s finally getting to a point where I want to start sharing it with other people.

I’m trying to make Souwede feel like its own thing instead of just copying Windows, macOS, or another Linux desktop.

So I wanted to ask:

What’s a feature you’ve ALWAYS wanted to see in an operating system?

It can literally be anything. Something that would make your workflow easier, a cool customization feature, better file management, gaming stuff, privacy features, system tools, or even some completely crazy idea.

I’m looking for ideas to potentially add to Souwede OS, so drop your suggestions below!

Souwede OS is just getting started.


r/C_Programming 1d ago

What's up with Chapter 7.7 Line Input and Output?

Upvotes

Im reading C Programming Language by Brian and Dennis, and they seem to be frustrated with the standards and the implementation of fget()

Here are a few excepts as examples:
Normally fgets returns line; on end of file or error it returns NULL. (Our getline returns the line length, which is a more useful value; zero means end of file.)

Confusingly, gets deletes the terminating '\n', and puts adds it.

For no obvious reason, the standard specifies different return values for ferror and fputs.

The tone changes from the rest of the book, and they seem to express a lot of frustration/displeasure with how these functions operate, but wouldnt Dennis have a hand in their design as he created the C language?


r/C_Programming 1d ago

How do you keep h files and C files in sync??

Upvotes

hi, beginner in C, coming from JavaScript and rust. one thing I can’t get used to is how to keep h and c files in sync.

i often find myself having to copy the functions from my C file to the corresponding h file and manually delete all the definition and put a “;” there. or if I am iterating on a function, and ending up having to change the signature, I’d have to remember to do that in the h file as well.

another thing is with rust and js when you write a function most often the lsp can search through the code and autoimport the package you need on top of file. With C so far I’ve had to rely on the internet to find out exactly what header file I need to include.

surely I am missing some kind of plugin or some clever ways that experienced C programmers are using?


r/C_Programming 1d ago

Question Should I use nested structs, separate structs, or union nested in a struct for this?

Upvotes

I am doing my first game-type project in C. I am having trouble making a decision regarding handling UI. I am awful at explaining things and new to this so please bear with me.

I plan to have a struct UIElement that contains information related to a particular element. However, there will be different types of elements, such as Text, Texture, Color and whatnot. They will also contain a pointer to an array other UIelements belonging to them, for things such as a buttons on a window.

I am stuck between the following implementations for this:

  1. Make a struct "UIElement" that has information that every element will have (such as position)., then have other structs defined such as "TextElement" that will have a pointer to a UIElement as well as Text-specific information.

  2. Use enum and nested union within the UIElement struct to allow different instances of the same struct to have only the relevant data necessary for them. (Each element has enum for it's type within it)

  3. Just have different structs "TextElement", "ColorElement", "TextureElement". Doing this I believe I would have to use void* to store pointers to elements and cast them accordingly.

After writing this, option 2 seems like the best option, but the simplicity of 3 sounds useful, albeit bad in the long run. If I am overlooking a simple way to do this, please let me know.


r/C_Programming 1d ago

Question How do functions that "initialize" some values and memory work only returning an irrelevant value?

Upvotes

For example, SDL's SDL_INIT() takes an integer parameter and returns a bool, how can returning a bool "initialize" a library and allowing me to do stuff with that library?


r/C_Programming 22h ago

Project 2D graphics library (beginner friednly)

Upvotes

I have been working on library called "fofo" it's graphic library based on SDL3 and it's beginner friendly so just by knowing python or C++ basics you could make any game/app you want!. i just released V0.1 so it may have bugs or things need to be improved so give me feedbacks and comments what it need to be added to fix/add that in future updates <3

link in the pinned comment.


r/C_Programming 1d ago

SDL palette and SDL_SoftStretch strange behavior

Upvotes

Hello everybody!

I'm working on a sample game on my spare time, that you can find here, trying to achieve a fade in/out effect using palettes over indexed (8bit) surfaces with SDL 1.2 (Yes, I know it's old, I'm planning to upgrade to 3 whenever my time permits...).

My goal is to achieve a classic nes style fade in/out effect, by making every single color in the palette darker or lighter gradually.

The app supports 2 arguments, --sw to make use of SDL_SWSURFACE flag, and --doublescreen to make use of SDL_SoftStretch.

By using only --sw, I saw the colors on the screen fading in a "strange" manner compared to
--doublescreen, that shows them fading from black to a more clearer version, until reach the original one, as I expected.

So I compared the surfaces structures values and palettes with and without --doublescreen, and saw no apparent differences, and I'm out of ideas at the moment...

Anybody has any suggestions on what cause this behavior over the colors?
Thanks in advance!

Edit: Please, since I don't want any AI usage in this project, avoid any AI suggestions, human interaction are prefered instead, thanks.


r/C_Programming 2d ago

Question How to - bit manipulation?

Upvotes

I know the bitwise operators:

1 & x - 'replicate' the existing bit
0 & x - turn off the bit
1 | x - turn on the bit
0 | x - 'replicate' the existing bit
1 ^ x - flip the bit
0 ^ x - 'replicate' the existing bit
~x - flip the bit
1 << x - shift to the left (multiply by 2)
1 >> x - shift to the right (divide by 2)

All of these basic operations are crystal clear. However, I am having trouble building actual masks out of these. I'm thinking too iteratively. How do I go through a number bit by bit and when is that actually needed? I tend to overcomplicate simple things.

int size = sizeof(x) * 8;
int mask = 1; // 0x00000001

for(int i = 0; i < size; i++)
{
// some mask operation with x
mask <<= 1;
}

I assume this would be good?

Okay but what about swapping the values of 2 different bits? Or what if I am working with bytes instead, then 8 sequential bits need to be swapped in 2 different positions, how do I do any that?

I am thinking of making a mask, moving to the 1st bit, copying it into some temporary variable, going to the 2nd bit, copying it into some other temporary variable, somehow replacing those variables in those positons. This sounds unnecessarily complicated but I couldn't think of another approach right now, this is generally the issue with a lot of things regarding bits. If any of you have some tips, genuinely useful shortcuts and how to's, I'd be very grateful!


r/C_Programming 2d ago

How to get Code Review?

Upvotes

Hello yall,

just wondering if there was a community where I can share my code to get advice and such, so like a Code Review.

This might also be another excuse to look at other peoples code and such, but I mainly want to get advice for my code.

Im not really familiar with the coding community, I just code and make projects by myself as a hobby.

cheers, and have a good day.


r/C_Programming 3d ago

Question Building a simple declarative TUI lib in C (FTXUI-inspired) how do you avoid callback hell in C?

Upvotes

Hey all,

I'm working on a TUI library in C just because I love how simple C is.

I know there are mature options like ratatui, bubbletea, vaxis, notcurses, etc. But I don't want to learn Rust just to build a TUI, and I don't really like bubbletea's Elm-style Update() -> string thing. The one I like best is FTXUI, but it's C++.

I want something simple + declarative in plain C. Right now my API looks like this:

```c

include "include/tui.h"

void btn_cb(void *ud) { tui_vbox(.gap = 1) { tui_label(.text = tui_str("Clicked")); } }

void draw(Tui *tui, void *ud) { tui_button(.text = tui_str("Click Me"), .bg = tui_color_rgb(255, 0, 0), .on_click = btn_cb); }

bool event(Tui *tui, const TuiEvent *ev, void *ud) { if (ev->type == TUI_EVENT_QUIT) return false; if (ev->type == TUI_EVENT_KEY && ev->codepoint == 'q') return false; return true; }

int main() { Tui *tui = tui_init(.title = "Tui application"); int counter = 0; int rc = tui_run(tui, .on_draw = draw, .on_event = event, .async = true, .userdata = &counter); tui_close(tui); return rc; } ```

It works, but I already hate the .on_draw, .on_event, .on_click callback split. It feels like callback hell waiting to happen once the UI gets bigger.

Question for C folks:

  1. Any C tricks / macro tricks to make this more declarative and remove callbacks? I'm already using designated initializers + compound literals tui_button(.text=...) and for-loop scoping for tui_vbox { ... } like FTXUI.

  2. How would you do state + events without on_click everywhere? Immediate-mode? Return an action enum instead of callback? Something else?

  3. Any small C TUI libs that do declarative UI well that I should steal ideas from?

Thanks.


r/C_Programming 2d ago

Data container - old newbish project revised

Upvotes

Some time ago I posted here my C implementation of a dynamic data container (vector like object):

https://github.com/andrzejs-gh/CONTLIB

I revised it, if anyone's interested take a look. Any feedback and tips very much welcome.


r/C_Programming 4d ago

Etc I actually had a laugh yesterday

Upvotes

I was coding up some piece that is supposed to rapidly parse millions of text logfiles. A file gets read into a buffer, and then the parser goes to work, peppering the buffer with zeros and building linked lists with pointers to the relevant bits, using two passes across the whole buffer. This was easy but I was unsure if I should use a different approach for efficiency. So I wrote a minimal test and measured the time for one logfile and spit out timestamp deltas for filling and chopping up the buffer, respectively. The results in milliseconds:

25.4
4.7

Not great for a 30kB file but the important message is: The parser isn't what needs to be optimized, for now anyway. Maybe it's the progressive realloc()ing of the buffer as it grows (RAM isn't free any more in AI times you know). But then I noticed that the program was still running under valgrind. After I took that out, I got:

0.0
0.0

I had to increase the decimal digits to see the microseconds. I found that hilarious. My colleague wondered what was wrong with me. I started C on a 2MHz/32kB machine. 25 ms read time for 30kB is still "pretty fast" in my book.

BTW, the speed of the incremental chunk-wise fread()/realloc() cycle is surprisingly immune against chunk size. Between 100 bytes and 10k it's not even a factor of 2.

[EDIT] The file size is not known beforehand. The data will be fed into this system by repeated calls to a user-supplied callback function. And realloc() seems to be dirt cheap if you don't let production code run under valgrind ;-)

[EDIT2] People keep commenting on optimal alloc / realloc strategies. Fact is: It doesn't matter(*). I'm reading files that are normally 25kB in increments of 1kB (a number I pulled out of my ass) and can't measure a difference that matters(*) if I use 100 bytes. I need some open-ended reading possibility because the occasional (and most interesting) log files can grow to several 100k in case something goes wrong with the process being logged.

(*) For my use case on this machine

I'm actually not surprised: Due to its ubiquity I'd expect dynamic memory allocation to be an aggressively optimized process in any OS. No wonder valgrind's monitored substitute is about 1000 times slower.


r/C_Programming 3d ago

Discussion Setting up c on windows.

Upvotes

Can somebosy walk me tru setting up c and clangd on windows ice tried for a day or 2 but cant get it right with kate,some help whuld be really apreciated.


r/C_Programming 3d ago

Sharing my Project is From Perceptrons to LLMs in C99 from Scratch

Upvotes

Hey guys so I’ve been working on this most of the year, it’s a path from Perceptrons to LLMs in pure C, without any libraries or anything. I made it cause I wanted to understand how LLMs work inside and I can think in C, so I used that and C gives me insight pulling a library in something like python dosent. I even ran the final project training and all on an MCU and it took up less than 1% of its memory! You can read that article here:

https://rvembedded.com/blog_post/13/

Or you can skip the hallabalu if you’re not into embedded targets and just go to the repo and if you like read the book I wrote as I worked through for free:

https://rvembedded.com/products/ai-from-scratch-in-c/

(For some reason I can’t link the GitHub, so click this link and click ‘read online now’ and if you want the repo just ask me and I’ll put blow I guess)

Due to a series of events like my article explains, rather than staying in infinite polish mode, I’m sharing for my fellow C programmers to enjoy!


r/C_Programming 4d ago

Question Question about alignment in a custom memcpy implementation

Upvotes

I'm implementing my own memcpy as an exercise.

My current approach is:

  1. Copy bytes until dst reaches a 4-byte-aligned address.
  2. Copy 4 bytes at a time using uint32_t.
  3. Copy the remaining bytes one by one.

I understand that this optimization works nicely when src and dst have the same alignment offset, e.g.:

src = 0x1001
dst = 0x2001

src % 4 == dst % 4

What I don't understand is why I can't simply perform an unaligned 32-bit load/store when the offsets are different.

For example:

src = 0x1001
dst = 0x2002

Why can't I simply do:

uint32_t x = *(uint32_t *)src;
*(uint32_t *)dst = x;

This seems like it should copy exactly the desired 4 bytes.

I understand that unaligned accesses may be slower, fault on some architectures, or have restrictions for MMIO. But assuming I'm on an architecture where unaligned 32-bit accesses are supported, is there actually a correctness problem?

I'm trying to understand the fundamental reason rather than just memorize the "same alignment" rule.

Thanks!


r/C_Programming 3d ago

C methology

Upvotes

Why in C/C++ is not very often use notation of framework, and instead is used libraries?


r/C_Programming 4d ago

Happy to share that my Valkey PR #3105 has been approved!

Upvotes

https://github.com/valkey-io/valkey/pull/3105

Contributed the IFNE option to the SET command.

Thanks to the Valkey community for the review and feedback!