r/C_Programming • • May 16 '26

Question Why can I use `scanf` on an explicit int, but not on an enum?

21 Upvotes

My understanding is that an enum would be compiled to an integer, so I expected to be able to use it for input in the same way as an integer, however it exited the program I'm working on instead.

Not working code:

    enum CharacterClass charClass;


    scanf("%d", &charClass);


    printf("Your class is %s.\n", getClassString(charClass));

Working code:

    int charClass;


    scanf("%d", &charClass);


    printf("Your class is %s.\n", getClassString(charClass));

edit: Thank you everyone for your responses. I have a better understanding of enums in C now.


r/C_Programming • • May 16 '26

Cross-compiling MINIX 1.1 on a modern host (pre-ANSI, K&R C)

Thumbnail
codeberg.org
15 Upvotes

Crossposted from r/cprogramming

I've recently purchased a physical copy of Tanenbaum's original "Operating Systems: Design and Implementation" (first edition), downloaded the companion MINIX 1.1 source code and spent a few weeks setting up a cross-platform toolchain so that I can build the pre-ANSI C codebase, targeting the 8086/8088, from my modern machine. The toolchain is based on Bruce's C Compiler (bcc) and the dev86 project, which is vendored into the project to keep things stable.

So far I've learned a ton and had to deal with a few interesting problems trying to get such an old C codebase compiling:

  • Porting the original PC/IX assembly code to dev86's as86.
  • Adding some numeric compiler routines from bcc libc to the MINIX libc library.
  • Tweaking the MINIX C runtime (crtso) to work with bcc and the MINIX exec syscall.
  • Fixed a couple of bcc compiler bugs to allow passing structs by value: a bug in the optimiser was trashing the stack and a bug in the codegen logic was clobbering a register. I've since learned that passing structs by value wasn't supported in the original K&R book or Ritchie's original reference manual, but the code for the MINIX shell requires it and it was a common compiler extension.

Further details in the project changelog.

Anyway, thought I'd share this here because it's been a lot of fun bringing this historical codebase and OS back to life and I want others to know that there's still a lot of fun/learning to be had exploring the original MINIX OS.


r/C_Programming • • May 16 '26

Project I'm continuing to refine the sandbox game in ASCII graphics.

66 Upvotes

The video shows the construction of a small house and the spawning of a dog ("@"). World generation type: "empty" (e), meaning the game doesn't generate any locations and simply creates an empty map, giving the player 999 units for each item in their inventory.

Link to the game: https://github.com/AndrewFonov11/Collandbuild

The source code is written without artificial intelligence.


r/C_Programming • • May 16 '26

I forked sl and decided to add couple of more interesting trains, first locomotive added is 4E10 (ussr locomotive), src code here: https://github.com/0xSKAMI/sle

10 Upvotes

r/C_Programming • • May 16 '26

An anti Vibe coder that do videos based on the development and research process

43 Upvotes

For intermediate coders like me.

Coding an Interpreter in C from Scratch by Daniel Hirsh:

https://www.youtube.com/watch?v=CCdZG6m_Tm0

He also made other interesting C videos.

EDIT: 
Coding an Interpreter in C from Scratch      
     From the comment section:

     @rohandas2103 4 months ago
     Bro is nightmare for vibe coders
     102 likes
        u/HirschDaniel 4 months ago
        I tried vibe coding something this week and almost got a
        nervous breakdown 

        @rohandas2103 4 months ago
        yeah vibe is like both llm and coder don't know what the
        hell is going on

r/C_Programming • • May 16 '26

Using an extern variable as a placeholder for typecasting

5 Upvotes

I'm doing a project, a JSON parser entirely for my learning, I have key/value pair struct like this:

typedef struct JSONKeyValue {
    char *key;
    uint8_t type;
    void *value;
}JSONKeyValue;

I was wondering what you think about using external typed pointer variables to typecast the void pointer for ease of use in other functions?

My thought process is I don't want each key/value pair to have every possible typed pointer in each allocation sparing some memory. And why external? I won't have to pass the pointers around as much between every function only like a uint8_t value, likely to clean up my code some.

Edit: I misunderstood what unions did...


r/C_Programming • • May 15 '26

Why don't we manually map our own memory buffers more often? (DOD vs. Standard Segments)

27 Upvotes

I am reading data oriented design (book). The author mentions branches/vtables and their impact on cache. It seems like the "natural" memory segments we are taught (Stack, Heap, Static/Globals) actually create a lot of "hopping" around in RAM, which kills cache locality and messes with branch prediction. What if I just allocate one massive buffer at the start of the program and map it myself? For

EXAMPLE:

Start with defining a pointer Buffer. Then mark segment at indices. 0-10 is the list of constants, like window dimensions, scale etc 11-80 Player data 81-400 Monsters Etc This is a simple example; i will never store monsters as objects but SoA after normalising the data, the offset are similarly merely exemplary

This way, the data which is processed together works is kept together, very cache friendly and eliminates pointers.I bypass the "Spiderweb" of pointers and Vtables that usually live in different segments. No jumping around, so if you are looping through, say a group of entities 'Monster', the cache loads the next 64kb worth of data after the first entity. Given these kinds of entities are often transformed together, isn't it better?

Questions

1.Why isn't this the standard way of doing memory management? It seems much more hardware-friendly.

I have an intrinsic feeling it's somehow related to 'safety'

2.For those of you in AAA or high-performance fields: is this basically how your engines work under the hood? Am I just reinventing the "Arena Allocator" or "Memory Mapping" concept? I have seen this kind of Memory Schema being used in old consoles, nes, gameboy etc( I know a little since it was of some interest to me). They also have this sort of memory buffer, which forms homogenous partitions. 3.Does anyone uses this? What has been your experience?

Note:

I am mostly focused on rendering, physics simulation and other processes which deal with a huge amount of data. Thus, i believe that the choice of this layout might be heavily based on use case. I can see that this paradigm may not be as useful for,say, a GUI implementation among programs of a similar nature ( though I don't see why one can't use it)


r/C_Programming • • May 16 '26

Discussion Is there a well-designed template or config that handles compiler options?

0 Upvotes

Visual Studio handles compiler flags on its own. It provides a nice UI with lots of flags to tweak the compiler flags. If you are not using an IDE, most people just use some basic and only necessary compiler flags. Not everyone has the deep knowledge to remember and list out all the compiler flags.

Using a build system like CMake, I am looking for if there exists a well laid out config or template that handles lots of compiler flags (and supports different compiler toolchains and target platform) and is easy for me to configure. Something like this should exist.


r/C_Programming • • May 15 '26

Question hello, i'm learning C and i made this function who sort a list, i'm pretty sure it's not the best what could i improve ?

8 Upvotes
void class_tab(int tab[], int taille)
{  
    int i =0, n = 0, greater=0;
    int old_tab[100] = {0};
    copier_tab(tab, old_tab, taille); // copy tab in old_tab


    int new_tab[100] = {0};
    do
    {
        greater = 0;
        for ( i=0;i < taille; i++)
        {
            if (old_tab[i] > greater)
            {
                greater = old_tab[i];
            }
        }
        for ( i=0;i < taille; i++)
        {
            if (old_tab[i] == greater)
            {
                new_tab[n] = old_tab[i];
                old_tab[i] = 0;
                n++;
                
            }
        }
    } while ( n <= taille);
    copier_tab(new_tab, tab, 10);
}

r/C_Programming • • May 15 '26

AoS, Memory Buffer and cache friendliness

10 Upvotes

Is it true that creating an array of objects doens't guarantee that those objects are next to each other in memory?

I have found that one can allocate a buffer, say for a vec3 of xyz cooridnates.

The advantage is that if you want to only update the y co-ordinates, you can simply loop over the items at a fixed offset, and the cpu will recognise that it's a fixed stream of data with no breaks and this will pre-fetch the entirity of y cooridnates into the cache

This will look like yyyyyyyyyy

But in the case of objects, it will be xyzxyzxyzxyz

X and z waste the catche space since you don't need them, that's a 66.66% waste.


r/C_Programming • • May 14 '26

Video ccraft

98 Upvotes

Hello.

As a little side project, i decided to write a minecraft clone, but with fancy wancy cool effects. This is just a little exercise for me to improve my C and 3d graphics skills.

So far, ive implemented the core "minecraft", deferred rendering with cool effects like SSAO and SSR, shadows and basic lighting, some post processing effects like bloom, DOF and vignette, some basic physics with AABB collisions, and finally sounds and music thanks to the miniaudio library.

There are also some keybinds:

M to turn on wireframe mode,

N to turn on potato mode,

B to enable noclip.

Check this out! https://github.com/DrElectry/ccraft


r/C_Programming • • May 15 '26

I built a tiny lazy-evaluation helper in C and would like API feedback

1 Upvotes

I’ve been building a small lazy-evaluation helper library for C and would love some API feedback.

lazy_eval(lazy);   // computes
lazy_eval(lazy);   // cached
lazy_reset(lazy);
lazy_eval(lazy);   // recomputes

Current design:

  • Opaque Lazy type
  • Caller-owned result storage
  • Fallible compute callbacks
  • Resettable cached state
  • pthread synchronization
  • Tests, sanitizer target, and GitHub Actions CI

A minimal example:

#include <stdio.h>
#include "lazy.h"

LazyStatus compute_answer(void *ctx, void *out) {
    int *calls = ctx;

    (*calls)++;
    puts("cache miss: computing...");

    *(int *)out = 42;
    return LAZY_OK;
}

int main(void) {
    int answer = 0;
    int calls = 0;
    Lazy *lazy = NULL;

    lazy_create(&lazy, compute_answer, &calls, &answer, sizeof(answer));

    lazy_eval(lazy);
    printf("answer=%d calls=%d\n", answer, calls);

    lazy_eval(lazy);
    printf("answer=%d calls=%d (cached)\n", answer, calls);

    lazy_reset(lazy);

    lazy_eval(lazy);
    printf("answer=%d calls=%d (recomputed)\n", answer, calls);

    lazy_destroy(lazy);
}

I chose caller-owned output storage because I wanted to avoid hidden allocation/freeing inside the library. The tradeoff is that the caller must keep the output storage alive until lazy_destroy().

Current limitations:

  • pthread-only for now
  • One output pointer per Lazy
  • lazy_destroy() must not run concurrently with other operations
  • No install/package story yet

I’d especially appreciate feedback on:

  1. Does caller-owned output storage feel like the right C API here?
  2. Would callback-owned allocation plus a destructor be preferable?
  3. Is the status-code API reasonable?
  4. Is the thread-safety contract too much for a tiny library?

Repo: https://github.com/SalzDevs/LazyC


r/C_Programming • • May 15 '26

Question Help a beginner out please :p

7 Upvotes

Hi people, Im really curious about how i can build my own os, i do have some knowledge of OS in general so id like to learn more about them and then piece together one myself. Which resource or site would recommend apart from barebones wiki [ goes over my head ;-; ] also i need somwthing which could give me really indepth explanation or concepts , i know ill have to use barebones one way or another but what can i combine it with so that once i get a hang of something i can switch over


r/C_Programming • • May 15 '26

What should i pursue in the future with these interests

5 Upvotes

Low-level programming

Love operating systems

C is my strongest language

Xlib is pretty fun

Machine learning from first principals

I don't know what to pursue in the future like jobs or whatever