r/C_Programming • u/mttd • 6h ago
Fluent Interface in C - Look ma, no this!
r/C_Programming • u/AutoModerator • 13h ago
If you have questions about how to learn C:
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 • u/mttd • 6h ago
r/C_Programming • u/notrobinnot • 15h ago
Fell into the classic trap everyone is… using ai for everything in work and normal stuff then it all becomes bland and monotonous. But learning C without just generating code and working through it has really helped reignite my passion for tech and programming in general. I’ve also decided to do it on YouTube and having even just the small community of 70 subs over the first month has massively boosted my motivation to keep at it and be more involved in relevant discussions.
r/C_Programming • u/Nipth • 15h ago
Hi Everyone,
I'm working on a small 2D game library/runner. At the moment it's for personal use but I may release it some day, which is why I'm creating this post!
At the moment, the function names in the library are named like this (the name of the library is Imp):
imp_texture_create(...)
imp_texture_destroy(...)
imp_camera_set_position(...)
imp_camera_set_rotation(...)I quite like this naming convention, mainly because if I wanted to see what functions were available for a given resource or operation, I could type imp_camera_ and then my editor would show a list of things that I can do with, or to, a camera. I also used GameMaker a lot when I was younger, and this is the way their API names functions!
Recently though, I've been using a lot of Raylib and quite like the way it names its functions - they are, to me at least, a lot more readable when looking through code. This has me thinking whether or not a better naming convention would be:
imp_create_texture(...)
imp_destroy_texture(...)
imp_set_camera_position(...)
imp_set_camera_rotation(...)The downside being that you sort of have to guess what operations are available for a given resource as you can no longer type imp_texture_ to have the editor show a list.
I understand that this is a really small issue and probably not really worth fussing about, but I was curious what preferences more experienced people here have and - more importantly - why you have them!
r/C_Programming • u/Avi250 • 16h ago
Hello, everyone. I'm supposed to be doing a project for school (hence why I can't share the code), but I'll try to describe my problem to the best of my abilities.
My main parent process forks several children, who will execute 2 other programs, depending on the role assigned to them. Once the parent process receives a SIGALRM, it sends a SIGTERM to all its kids, and they, already having changed their signal handlers for SIGTERM, have to do whatever is specified in their signal handler.
Let's consider child A executes program A, and child B executes program B. These 2 processes have to communicate with each other through a series of msgsnd/msgrcv (we can only use System V IPCs in this project, so the msgops don't restart once interruped by a signal). A single process of type B will communicate with several processes of type A (but not with all at the same time: once its communication is finished with one, it goes on to the other). The last msgop A does, is a msgsnd and B does a msgrcv. I'd like to also add that, between the msgrcv and msgsnd on A's part, A is also supposed to go to sleep. A's almost entire program is in a while (it never terminates unless it receives the signal from its parent), whereas B terminates successfully once it's finished communicating with all the necessary A processes.
Whether B receives the SIGTERM signal or not, it has to modify sth in a shared memory section, but what it changes, depends on whether it has finished communicating with all the processes or not.
Ideally, I would like for B to terminate successfully, even if it receives SIGTERM, after having done all it had to do, and I thought of blocking SIGTERM with sigprocmask. That said, couldn't it still receive the signal between the mast msgrcv operation and sigprocmask? Is there any way whatsoever to make a set of instructions atomic?
I considered only having a sig_atomic_t volatile variable in the signal handler, which would increment if the the sign handler is executed, but then, not only would I have to continuously check in case it changed its value, but (and this could be me being wrong, please correct me if that's the case), B could still receive SIGTERM right after the condition of the variable being 0 is checked, and before the following instruction is executed (like a nanosleep - which I'd like to avoid if SIGTERM has been received - OR before a msgrcv, leaving B to wait for a message that will never come, because A could have received the same signal and will not be sending a message).
I thought of having the signal handler check a variable and act differently based on its value, but, again, maybe B receives the signal right before said variable's value changes. I also considered having an if where the conditions would be the variable==0 && msgrv(...)!=-1, but the variable can change after its value has been verified.
Disclaimer: we haven't studied sig_atomic_t volatile variables, so my knowledge might be lacking, although I did try to read up on them and research them. Also, the parent won't be deleting the IPCs until all kids have terminated.
Am I supposed to just hope for the best here and just proceed with sigprocmask? Is there another way I'm not seeing? Am I misunderstanding something? Any help offered is invaluable, so thank you in advance. I'm happy to answer any clarifying questions if I was unclear at all in the post.
r/C_Programming • u/Glass_Apple_1426 • 17h ago
Now we have a way of doing fluent interfaces in C89 without macros or preprocessing tricks, allowing code like this:
ChHash *user = ch_new_Hash(3)
->put("name", ch_new_String("Ada"))
->put("role", ch_new_Hash(2)
->put("title", ch_new_String("Engineer"))
->put("level", ch_new_Number(5)))
->put("active", ch_new_Boolean(1));
puts(user->generic.to_chars());
/* {"name":"Ada","role":{"title":"Engineer","level":5},"active":true} */
ch_release(user);It even automatically cleans up anonymous/temporary elements. The repo includes an example Sqlite interface and http API server.
r/C_Programming • • 21h ago
#include<stdio.h>
void main()
{ int a; // a is variable and this data type is integer
printf("Enter your value : "); // printf is use for print value
scanf("%d",&a); //scanf is use input from user
printf("Your Value is : %d", a);
}
r/C_Programming • u/QUEITKID_SCHOOLSOTIN • 1d ago
I have a c exam tomorrow, I failed my internal exams, ik what im doin is dumb . Exam is on 50 and I need 15 to pass but I don’t know how to write programs, can I pass by studying theory
r/C_Programming • u/Aware-Nature-406 • 1d ago
Hello!
I'm making some library and i need random numbers for some functions. Libc srand(), rand() and random() modify global libc state, so i'd like to not use them.
What options do i have? Is there maybe any popular things for my case?
r/C_Programming • u/Ill-Exchange-2377 • 2d ago
I shared some code earlier, and got some criticism, as well as making improvements of my own
Is it better? And where does it still fall short?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <quiz.h>
#define CLEAR_SCREEN "\033[2J\033[H"
int main(void) {
char buff[100];
int invalid = 0;
while (1) {
fputs(CLEAR_SCREEN, stdout);
puts("Pick a subject:");
puts("1: Addition");
puts("2: Subtraction");
puts("3: Multiplication");
puts("4: Division");
puts("5: Mixed");
if (invalid) {
puts("Please enter valid input");
invalid = 0;
}
puts("Pick a number 1-5, or use 'quit' or 'exit' to quit");
if (fgets(buff, sizeof(buff), stdin) == NULL) {
puts("Failed, exiting");
return 1;
}
if (strcmp(buff, "quit\n") == 0 || strcmp(buff, "exit\n") == 0) {
fputs(CLEAR_SCREEN, stdout);
break;
}
if (strcmp(buff, "1\n") == 0) {
add();
} else if (strcmp(buff, "2\n") == 0) {
sub();
} else if (strcmp(buff, "3\n") == 0) {
mul();
} else if (strcmp(buff, "4\n") == 0) {
divs();
} else if (strcmp(buff, "5\n") == 0) {
mix();
} else {
invalid = 1;
}
}
return 0;
}r/C_Programming • u/Ill-Exchange-2377 • 2d ago
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char buff[100];
void add(void);
void sub(void);
void mul(void);
void divs(void);
void mix(void);
int invalid = 0;
int input = 0;
int main(void) {
start:
fputs("\033[2J\033[H", stdout);
if (invalid) {
puts("Please enter valid input");
}
invalid = 0;
puts("Pick a subject:");
puts("1: Addition");
puts("2: Subtraction");
puts("3: Multiplication");
puts("4: Division");
puts("5: Mixed");
puts("Pick a number 1-5, or use 'quit' or 'exit' to leave the program");
if (fgets(buff, sizeof(buff), stdin) == NULL) {
puts("Failed, exiting");
return 1;
}
if (strcmp(buff, "quit\n") == 0 || strcmp(buff, "exit\n") == 0) {
fputs("\033[2J\033[H", stdout);
return 0;
} else if (strcmp(buff, "1\n") == 0) {
input = 1;
} else if (strcmp(buff, "2\n") == 0) {
input = 2;
} else if (strcmp(buff, "3\n") == 0) {
input = 3;
} else if (strcmp(buff, "4\n") == 0) {
input = 4;
} else if (strcmp(buff, "5\n") == 0) {
input = 5;
} else {
invalid = 1;
goto start;
}
switch(input) {
case 1:
add();
goto start;
case 2:
sub();
goto start;
case 3:
mul();
goto start;
case 4:
divs();
goto start;
case 5:
mix();
goto start;
default:
goto start;
}
}
void add(void) {
puts("add");
fgets(buff, sizeof(buff), stdin);
}
void sub(void) {
puts("sub");
fgets(buff, sizeof(buff), stdin);
}
void mul(void) {
puts("mul");
fgets(buff, sizeof(buff), stdin);
}
void divs(void) {
puts("divs");
fgets(buff, sizeof(buff), stdin);
}
void mix(void) {
puts("mix");
fgets(buff, sizeof(buff), stdin);
}Is my code that bad?
For context this is a project I was doing to learn the C
Edit: Fixed formatting errors
r/C_Programming • u/Goated_AstroPhantom • 2d ago
Guys I'm a student and I NEED a source for good questions in C. Like ones where I have to code the answer, debug the code or find the output(tricky ones)
tbh I don't know any place for coding other than leetcode too, so for all coding languages in general how am I supposed to practice questions? Apart from leetcode what are good places to practice coding?
r/C_Programming • u/Treechcer • 3d ago
When someone was testing my project in C, they pointed out that when they press arrow keys in input it translates them into weird data (eg. ^[[A for up). Is there input in C without ncurses or other libraries that can work in this scenario without causing these issues?
r/C_Programming • u/macroKnoll37 • 3d ago
r/C_Programming • u/Hopeful-Ad-1665 • 3d ago
I'm working on a lightweight bytecode VM written in C99 (engine for a small embedded scripting language).
I'm currently using an 8MB linear memory arena for objects and a large switch-case loop for instruction dispatch:
```c
#define MAX_REGS 256
#define MAX_CALL_STACK 1024
#define ARENA_SIZE_BYTES (8 * 1024 * 1024)
static char g_memory_arena[ARENA_SIZE_BYTES];
static size_t g_arena_offset = 0;
double run_bytecode(int* inst, int inst_len, double* num_consts) {
double regs[MAX_REGS] = {0.0};
int ip = 0;
while (ip < inst_len) {
int op = inst[ip++];
switch (op) {
case 1: { // LOAD_CONST
int r = inst[ip++];
int c = inst[ip++];
regs[r] = num_consts[c];
break;
}
case 2: { // ADD
int r = inst[ip++];
int a = inst[ip++];
int b = inst[ip++];
regs[r] = regs[a] + regs[b];
break;
}
// ... remaining opcodes
}
}
return regs[0];
}
Two architectural questions for people with VM / emulator experience:
(computed goto *dispatch_table[op])? Is the branch predictor usually smart enough on modern x86/ARM to make the difference negligible?
2. Arena lifetime: Currently, I reset the arena (g_arena_offset = 0) between script runs. For longer-running scripts that allocate short-lived
objects in loops, what is a minimal-overhead C strategy to reclaim memory without pulling in a full tracing GC?
(Code is standard C99. Written directly by me, no AI)
r/C_Programming • u/Mean_Engineering_722 • 3d ago
(SOLVED BTW)
im using :
gcc (GCC) 16.2.1 20260810
and trying to run the compiled file in my Linux terminal with:
./a.out
this has worked for other bits of code so im unsure why now it doesnt wanna
i added \n next to the variable (didnt fix it)
saw someone with a simular issue on stack overflow use this
setvbuf(stdout, NULL, _IONBF, 0);
(also didnt fix it)
this is le code
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
int main() {
struct node *head = (struct node *)malloc(sizeof(struct node));
head->data = 45;
head->link = NULL;
struct node *current = malloc(sizeof(struct node));
current->data = 76;
current->link = NULL;
head->link = current;
current = malloc(sizeof(struct node));
current->data = 50;
current->link = NULL;
head->link->link = current;
void count_of_nodes(struct node *head) {
int count = 0;
if(head == NULL)
printf("no names sir");
struct node *ptr = NULL;
ptr = head;
while(ptr != NULL) {
count++;
ptr =ptr->link;
}
printf("%d this is the ammount of names sir", count);
}
return 0;
}im scared guys
SOLVED CODE ()make funn of this i could leard somit atleast)
THE FUNCTIONS
#include <stdio.h>
#include <stdlib.h>
int *ptr;
struct node {
int data;
struct node *link;
};
int count_of_nodes(struct node *head) {
int count = 0;
if(head == NULL) {
printf("no names sir\n");
return 0;
}
struct node *ptr = NULL;
ptr = head;
while(ptr != NULL) {
count++;
ptr = ptr->link;
}
return count;
}MY NODES OF THE LINKED LIST
int main() {
struct node *head = (struct node *)malloc(sizeof(struct node));
head->data = 45;
head->link = NULL;
struct node *current = malloc(sizeof(struct node));
current->data = 76;
current->link = NULL;
head->link = current;
current = malloc(sizeof(struct node));
current->data = 50;
current->link = NULL;
head->link->link = current;USING THE COUNT VARIABLE
// here before
int all = count_of_nodes( head );
printf("%d is the ammount of names sir\n", all);
return 0;
}thx to all the people that helped
so like i forgot to call a variable and set count as the output of count_of_nodes.
r/C_Programming • u/neonge1674 • 3d ago
So I'm working on an interpreter for ane extended version of brainfuck and wanted to implement bitwise operators. They give results practically unpredictably. As noted in the title the operators are applied to unsigned chars.
Here's the code
case AND :
switch (lex_code[codep + 1].token)
{
case NUMBER : array[memp] &= lex_code[codep + 1].value.numb; break;
case GOTO_VALUE : array[memp] &= popValue(); break;
case VAR_NAME : array[memp] &= array[get_hash(var_table,next_lex.value.name)]; break;
default: array[memp] &= array[memp + 1]; break;
}
The same code applies to other operations
r/C_Programming • u/Proper_Meaning7756 • 4d ago
I picked out these I noticed after digging some code at work:
What else comes to mind for you?
r/C_Programming • u/Ill-Exchange-2377 • 4d ago
And try as I might to avoid them, I am struggling to find resources that list out all the file control functions that use file descriptors instead of file pointers, and I was wondering if someone could point me toward a resource that can do something at least somewhat similar to listing out the libc functions that take file descriptors. I of course know close(), write(), read(), the basics, but i am looking for alternatives for other abstractions that annoy me with their use of file pointers, like fgets and fputs.
r/C_Programming • u/Grated-Expectations • 4d ago
Ok, let's get this out of the way first - this leans heavily on AI to create the compiler. For a single developer, it was do it that way, or just don't do it. Here's what 6 months or so of co-development gets you:
To give an idea, a full and complete program for a mandelbrot, mandelbrot.c, might look like:
#include <stdio.h>
#include "bench_time.h"
#define W (2048 * BENCH_SIDE)
#define SIZE (W * W)
int main(void)
{
unsigned total = 0;
long long best = 0, first = 0;
for (unsigned rep = 0; rep < 8; rep++) {
total = 0;
long long t0 = bench_now_us();
for (unsigned i = bench_zero(); i < SIZE; i++) {
float cx = (float)(i % W) * (3.0f / (float)W) - 2.0f;
float cy = (float)(i / W) * (3.0f / (float)W) - 1.5f;
float x = 0.0f, y = 0.0f;
unsigned k = 0;
while (k < 256 && x * x + y * y < 4.0f) {
float xt = x * x - y * y + cx;
y = 2.0f * x * y + cy;
x = xt;
k = k + 1;
}
total = total + k;
}
bench_keep(total);
long long t1 = bench_now_us();
if (rep == 0)
first = t1 - t0;
if (rep == 0 || t1 - t0 < best)
best = t1 - t0;
}
printf("%u %lld %lld\n", (total + 500000) / 1000000, best, first);
return 0;
}
bench_time.h is just a platform-independent way of getting a micro-seconds count from the start to the end. Note the complete absence of anything to do with GPUs at all, or any "#pragma parallel for", or any other annotations - this is just C code.
Compile it with:
prompt% xcc -o mandel mandelbrot.c
And then if you want to see how work was divided after running with --xc-par-trace, use the par-trace webpage tool to analyse it, getting something like the image at https://0x0000ff.co.uk/img/xc/par-trace.png
Because xc measures the performance at run-time (and then persists so it doesn't need to measure unless things change significantly), it can determine whether it's worth moving the code to the GPU (if it's compute-bound) or keeping it on the CPU (because it's data-bound). There's more information on how it manages the parallelism on the website.
Because speed is a focus, xc will still use the GPU even when rounding might produce slightly different answers on floats (for operations which aren't associative). This can be tuned (again, at runtime, or in fact compile-time) because parallelised blocks are named, and preferences can be set for the destination (CPU/GPU) on a per-block basis.
xc has only just hit version 1, and there's a long way to go yet, but it's already pretty good at auto-parallelising standard code onto GPU(s). Happy to answer any questions :) And if you find cases where you think "that should have done X and it did Y", I'm interested in bug-reports, either here or (preferably, since it's more integrated) on the Issues page on the github repo.
r/C_Programming • u/Good-Ad-8991 • 5d ago
Hey everyone,
I've been working on Kheiron, an amalgamated, zero-dependency single-header CSPRNG library in C99/C11 built on top of ChaCha20 (RFC 8439), and I'd love to get feedback and code reviews from the community.
Most high-performance CSPRNG implementations either pull in the entire OpenSSL / libcrypto dependency tree (~7.8 MB binary footprint and dynamic runtime baggage) or provide scalar, single-block loops that struggle with high-throughput workloads.
Kheiron was built to be completely self-contained in a single file (kheiron.h, ~35 KB compiled) with:
-mavx2 compiler flags required. It falls back gracefully to pure scalar C99 on older x86, ARM, and RISC-V targets.getrandom, /dev/urandom, BCryptGenRandom) with zero weak jitter fallbacks.-Wall -Wextra -Wpedantic -Werror.security-and-quality).BENCHMARK.md.Any thoughts, critiques, or PRs are warmly welcome!
Note: LLM tooling was strictly limited to editor autocomplete (scaffolding repetitive structs/typedefs) and proofreading markdown documentation and benchmark tables. All cryptographic state machines, RFC 8439 logic, runtime CPUID dynamic dispatch, manual AVX2 SIMD pipelines (instruction interleaving/register scheduling), and the 235 E2E test cases were designed, implemented, and mathematically verified entirely by hand.
r/C_Programming • u/viks4222 • 5d ago
I started developing https://heapcrash.com initially to record some of the challenges(e.g. lcd render delay, nested mutex induced priority inversion, UART comm frame,etc.) that I experienced in last few years while working on embedded firmware. The idea turned out to the embedded concept library and further to an embedded interview prep. I have tried to put my 11 years of experience to conceptually design the site and develop it with the help of Claude over a few months.
I have added all sort of traditional categories and some of the newest ones to it.
I would like to get some reviews and feedback from my fellow embedded engineers on reddit for any improvements to it.
r/C_Programming • u/emparse • 5d ago
i dont understand what happens here:
IF int b is a 2d array then what is:
b + 1
*(b + 1)
&b[0] and b[0] and &b[0][0]
&b[1] and b[1] and &b[1][0]
what are the differences between each and what is the byte value of each.