r/cprogramming • • May 16 '25

Why code runs accurately only when 1 line is commented out?

0 Upvotes

Hi Guys. Wondering if anyone can explain to a noob why in the below code when I compile and run, it will create the basic encrypted number accurately only when I comment out the line "int flag = 0" (even when the related while loop for the flag is commented out). If I remove the comment on "int flag = 0" it just creates junk code?

#include<stdio.h>

int main (void) {

int digit_1, digit_2, digit_3, digit_4, number, temp, num, counter, encrypted_number = 0;

printf ( "%s", "Please Enter Number: " );
scanf ( "%d", &num);

//int flag = 0;

/*while ( flag == 0 ) {

    if ( num < 0 ) { 

        puts ( "Number Too Small" );
        printf ( "%s", "Enter New Number: " );
        scanf ( "%d", &num);

    } //end if

    else if ( num > 9999 ) { 

        puts ( "Number too large" );
        printf ( "Enter New Number: " ); 
        scanf ( "%d", &num);

    } //end if

    else {
      
        flag = 1; 

    } //end else

} //end while */

while ( counter < 4 ) {

        temp = num;
        printf ( "%s" "%d\n", "temp = num: ", temp ); 
        temp %= 10;
        printf ( "%s" "%d\n", "temp %= 10: ", temp ); 
        temp += 7;
        printf ( "%s" "%d\n", "temp += 7: ", temp ); 
        temp %= 10;
        printf ( "%s" "%d\n", "temp %= 10: ", temp ); 

        if ( counter == 0 ) {

            digit_4 = temp;

        } //end if

        else if ( counter == 1 ) {

            digit_3 = temp;

        } //end else if

        else if ( counter == 2 ) {

            digit_2 = temp;

        } //end else if

        else {

            digit_1 = temp;

        } //end else

        printf ( "%s" "%d\n", "counter: ", counter );
        counter++;
         num /= 10;
         printf ( "%s" "%d\n", "num /= 10: ", num ); 

         puts ( "" );

} //end while

printf ( "%s%d\n%s%d\n%s%d\n%s%d\n", 
"digit_1: ", digit_1, "digit_2: ", digit_2, "digit_3: ", digit_3, "digit_4: ", digit_4 ); 

encrypted_number = ( digit_3 * 1000 ) + ( digit_4 * 100 ) + ( digit_1 * 10 ) + ( digit_2 );

printf ( "%s%d\n", "Encrypted Number: ", encrypted_number );

} //end main

r/cprogramming • • Sep 01 '26

How to learn

0 Upvotes

I just started learning C about 5–6 days ago, and I had never coded before.

I completed the CS50 course, so I know the important concepts and have a basic understanding of how things work. But when it comes to actually implementing them, I feel like I’m at zero.

Now I’ve started learning C from the book The C Programming Language. I’m understanding some concepts, but not everything. I’d say I’m only understanding around 20–25% of what I read.

For example, I understand how "getchar()" and "putchar()" work individually, but when I see a program that uses them together, I don’t even understand 60–70% of the program.

I’m getting stuck, and it’s making me think that maybe only people with good logic can survive in programming jobs.

So, please guide me on how I should approach learning C correctly and develop my programming logic.


r/cprogramming • • Sep 23 '20

What am I doing wrong?

Post image
0 Upvotes

r/cprogramming • • Sep 13 '26

What is this code doing?

0 Upvotes

Hi, I found this code on another subreddit. I would like to know what is it doing.

int puts(char *);

int main() { struct { long a; long b; } s = {.a = *(char *)(int[]){1} ? 0x57202c6f6c6c6548 : 0x48656c6c6f2c2057, .b = *(char *)(int[]){1} ? 0x00000021646c726f : 0x6f726c6421000000}; puts((void *)&s); }

Now obviously I know it's unreadable, I would just like to know what are those hexadecimals strings doing.

I found similar codes that were writing to vram to print a message, is this doing the same thing? If yes, why is it so much more complicated instead of just writing the message to the video adress?

Thanks for the help.


r/cprogramming • • Jan 03 '23

Hiw do i write a program in c to calculate a+b a-b using function?

0 Upvotes

where a =100, b=50


r/cprogramming • • Feb 10 '22

Can someone tell me what's the problem is? The point of this project is to copy mystr2 to mystr1. And mystr3 is supposed to say "Hello World." And I took this project from my teacher, but it's not working for me, but it's working with my other teammates.

Post image
1 Upvotes

r/cprogramming • • Oct 04 '25

Don't know what I'm doing wrong

1 Upvotes

input : 16 should give output : 16 and input: 5 should give output : 8.94427190999915878564

and this is my code what am I doing wrong (input and output should be exactly what I wrote) :

#include <stdio.h>
#include <math.h>

int main() {
    int area;
    
    scanf("%d",&area);
    double omkrets = sqrt(area) * 4;
    printf("%.21g",omkrets);
    
    return 0;
}

r/cprogramming • • Aug 06 '26

What other features do you love to have in C?

1 Upvotes

Not sure whether this kinda questions were asked in this forum, in the past?

  1. I prefer to have set of APIs supported by separate header-files with a 's_' prefix, to provide only the safer versions of the existing standard APIs. Like #include<s_string.h>. Including this with string.h should throw an error.

  2. I would like to have a standard set of OS APIs, which can be used in any platforms/OSs. This is to avoid mani of the #if THIS_OS

  3. I would like to have a robust library for cross language FFI, to invoke the code-points/API of almost all of the popular programming language.

  4. Also the feature of labeled break and continue.

  5. Range datatype. 1..100,1..100..2(for say odd numbers)

What do you think?

What else?


r/cprogramming • • Oct 02 '25

Help

0 Upvotes

Where can I find the resources for learning the c language and the various libraries? A thousand thanks


r/cprogramming • • Mar 20 '22

HELPP PLSS

0 Upvotes

I am trying to write this C program that adds numbers until the user enters zero. I think my program is correct but I'm getting ridiculous outputs. I added 4+4 and the answer was 1074790400. I am lost and would appreciate some help. Thank you😭


r/cprogramming • • Apr 24 '21

Need help with this code, Its giving garbage value

Thumbnail
gallery
0 Upvotes

r/cprogramming • • Feb 21 '19

Can someone explain to me what to do in this,I’m not much of a math person, please help

Post image
0 Upvotes

r/cprogramming • • Jan 29 '25

After compilation is libc entirely present inside a.out??

0 Upvotes

when i compile a file how much stuff gets compiled i mean if i include stdio

does the stdio specific file get added to my a.out

or does my a.out expect the stdio to be present on the computer it will run on

also if the file is present in a.out

then does every application that uses the same libraries contains the compiled versions as well(
i basically mean that if i compile firefox with -lc flag to get libc in it

and i also compile libreoffice which also requires the libc

do they not use the same copy of libc or do they use the same copy of libc??

if they don't then isn't it wasted ram

if they do aren't they scared of any static variables present in these functions which might cause inconsistency?! after calling them in a different order than normal?!

Also i'm very new to this but there are few things i'm very very curious about

  1. what does the a.out file contain ( i want everything from what it contains to how it gets on my ram and is ran on my computer)

  2. What is x86 arm .. other things

  3. What is the kernel and what does it do ?!

if kernel is like middleware how is it not platform dependent?! How does linux kernel work on so many hardwares if it's a C program which are platform dependent

i have soo many questions about kernel cause i don't know anything about it

is there any good resource you can suggest me to clear my doubts about the topic or a very concize document/book/guide that will help me understand the basics of the kernel something every good computer nerd should know and put a clear picture of what kernel does in my mind?!

i'm always scared when anything related to kernel is being talked on forums :(

sorry for the rant thanks a lot :D


r/cprogramming • • Feb 04 '26

What is character input and output in simple terms?

0 Upvotes

Can someone explain what character input and output is and why it’s used?

putchar()

getchar()


r/cprogramming • • Apr 11 '26

I built a terminal-based interactive DSA library in C (~4000 lines) — the graph chapter nearly broke me, here's why

0 Upvotes

Project: full DSA library in C, terminal-based and interactive. Linked lists (singly, doubly, circular), stacks, queues, BST with traversals, graphs (adjacency matrix + adjacency list, DFS/BFS), infix-to-postfix + postfix evaluation, hashing, sorting, searching. Manual memory management throughout, Valgrind-clean.

GitHub: https://github.com/darshan2456/C_DSA_interactive_suite

The linked list and tree chapters were hard but survivable. Linked list reversal in-place taught me pointer discipline the hard way — silent heap corruption from one misplaced assignment is a very effective teacher. BST traversals broke and then permanently fixed my mental model of the call stack during recursion.

The infix-to-postfix chapter was different — not painful, but it's where I first understood what composing abstractions actually means in practice. I didn't use a standalone stack. I built a stack on top of my linked list implementation, then used that stack to implement the Shunting Yard algorithm. So the call chain was: algorithm → stack operations → linked list pointer manipulation — all code I wrote, all the way down. When it worked, I could trace exactly why it worked at every layer. That kind of end-to-end ownership over your abstractions doesn't happen when a language hands them to you.

But the graph chapter was a different category of hard entirely, specifically adjacency list representation.

Adjacency matrix is clean — a 2D array, index by vertex, done. I was comfortable.

Then adjacency list: conceptually it's just each vertex storing a list of its neighbors. Simple enough. In C it means an array of linked lists, where each list is dynamically allocated and grown independently. Suddenly you have:

- `struct Node** adjList` — a pointer to an array of pointers to linked list heads

- dynamic allocation for every single edge insertion

- pointer-to-pointer manipulation for list insertions

- freeing a graph means iterating every list, freeing every node, then freeing the array itself — in the right order

And the edge cases multiply fast. What happens when you insert a duplicate edge? What if the vertex index is out of bounds? What does a partial free look like when malloc fails halfway through building a graph?

It also made the complexity tradeoff concrete in a way Big-O notation alone never did. O(V²) space and traversal on a sparse adjacency matrix isn't just inefficient on paper — you feel it when you've implemented both.

Feedback on the implementation very welcome — especially around the graph memory management and whether my adjList structure could be cleaner.


r/cprogramming • • Feb 21 '26

This subReddit Is NOT for "ALL Things C" - Because The Mods Will Remove Your Post If You Want to Ask for Opinions + Question About Code-Style Preference

0 Upvotes

So, recently, I made a post in this subReddit because I wanted to ask all ov you all – the amazing C programmers ov Reddit – about your opinions on how procedural-style code should be structured. And I thought asking the C community would be a great thing, since C is a very procedural language…

… however, my post was removed with no explanation other than "Post is off topic", even though my post was trying to be meaningfully engage with the C community about their thoughts on procedural programming, but I was told by the mods than many ov you – fellow communitymembers ov this subReddit – reported my post as being off-topic, probably for no other reason than to take my question down.

I wanted to make this post to shed some light on the poor moderation from u/zhivago and/or u/Willsxyz, whichever ov them specifically is behind agreeing with the people whining about my post.


Now, this is what I wanted to ask about the whole time: for procedural-style programming, is it preferred to avoid hidden state mutations by, for example, returning signals and handling state directly with that signal, rather than handling state in (the) abstractions – or by some other means?

For example, consider this game ov hangman written in C:

void main() {
  // ...
  while(true) {
    writeMenu(&game, &stdoutWriter);
    // ...
    processNextLine(&game, &stdinReader);
  }
}

typedef struct Game {/* ... */} Game;

void processNextLine(Game* game, Reader* inputReader) {
  int bytes_read = readUntil(inputReader, &game->commandBuffer, '\n');
  // ...
  if(!game->started) {
    // ...
    switch(cmd) {/* ... */}
  }
  // ...
}

vs. the same program structured like this:

void main() {
  // ...
  while(true) {
    writeMenu(&game, &stdoutWriter);
    // ...
    Signal sig = processNextLine(&game, &stdinReader);
    switch(sig.type) {/* ... */}
  }
}

typedef struct Game {/* ... */} Game;

Signal processNextLine(const Game* game, Reader* inputReader) {
  int bytes_read = readUntil(inputReader, &self->commandBuffer, '\n');
  // ...
  if(!game->started) {
    return GameSignal { try_command: text };
  }
  // ...
  return GameSignal { try_to_reveal: char };
}

typedef union SignalPayload {/* ... */} SignalPayload;
typedef enum SignalType {/* ... */} SignalType;

typedef struct Signal {
  SignalType type;
  SignalPayload payload;
} Signal;

Please let me know what your thoughts are.

This post, in my opinion, is pretty on-topic to the C programming language, and thus this subReddit as a whole, so I should not see this post taken down (for that reason), or hear about anything reporting this post.

I can't wait to hear the good opinions ov the nice, C-programming people.
Cheers!


r/cprogramming • • Jul 22 '25

What exactly is relation between a pointer and an array?

2 Upvotes

I have read like 100 things right now about array, I know that we can represent arrays in a pointer-like fashion and that &array-name[0] is the address of the 0th element or the starting address of the array. But can we call an array a pointer?

I read this answer on StackOverflow and it seemed pretty valid to me yet I do not get it why are the above phrases/ used by people?

Some say it decays to a pointer when used in expression, some say array name stores address of first element of array

Are arrays pointer to first element in array?

Array decays into address of its first element when used in expression, so array name is pointer of first element of array??

Could I please get some explanation on this and some clarification or some resources on this topic? This whole thing is bugging me for the last days.


r/cprogramming • • Nov 03 '25

What is the saturation point?

2 Upvotes

Am learning C now, doing some problems day by day. When should i go to next language? At what point will i know “ok i have done enough problems and learnt good theory lets go to next language”?.


r/cprogramming • • Oct 23 '21

Questions from a novice

Thumbnail
gallery
0 Upvotes

r/cprogramming • • Mar 13 '25

Offline C compiler?

31 Upvotes

This is probably a stupid question, but I'm gonna have an 8-hour flight with no wifi, and I thought it would be a good time to work on my C assignments. Is there a way that I can, I guess, pre-load a compiler onto my Mac so I can still compile and execute code without being connected to the interwebs, and can I do this inside my IDE? And if so, where would I go to learn to set this up? thanks!


r/cprogramming • • Sep 01 '26

A project so great

5 Upvotes

Drop the best project you've made.

The one you are most proud of.


r/cprogramming • • Jul 14 '26

My real OS (D.eSystem 6.0.7 beta)

2 Upvotes

Hello everyone!!

D.eSystem 6.0.7 beta got a lot of polishing work. For example the versions 6.0.3 beta-6.0.6 veta were internial test versions,thats why 6.0.7 beta released.

D.eSystem 6.0.7 beta fixes major bugs in the calculator app and its the first D.eSystem which allows to change the wallpaper in the D.eShell.

D.eSystem 6.0.7 beta release on github: https://github.com/D-electronics-scratch/all_D.eSystem_versions/releases/tag/v.6.0.7_beta

Github main page: https://github.com/D-electronics-scratch/all_D.eSystem_versions


r/cprogramming • • Apr 02 '26

Any reason to avoid mixing camelCase and snake_case in a single codebase or even variable name; if the mixing is done with documented and concise rules, not arbitarly?

2 Upvotes

I've been learning C at a proper/deeper level lately. One of the first issues I ran into is the lack of namespaces in C[1]. People seem to mainly solve this by just using prefixes. Examples:

utils_sign()
utils_clamp()
window_foo()
core_entities_stuff()
etc....

Another example is 'vendor prefixes'. To minimize name collisions for your users when writing a library, you'd prefix everything with a short 2-3 letter name.

Example:

glCreateShader() //OpenGL
glewInit //GLEW
b2ClipSegmentToLine //Box2DC wrapper
//Box2d also does this in their Cpp code for typedef's since Cpp typedef's can't be namespaced (I think?)

Now, I'm also trying to implement OOP in C; by having the method just be a function prefixed with the class name taking the instance as its first argument. Standard stuff.

Example:

Array_get()
Player_attack()
Player_getHealth()

Notice the last one?

Basically I'd like to use underscores as a sort of 'logical-separator' in names, while using camelCase for 'readability-separator`.

For example in XmlParser the capital X tells you that its a class, but the capital P doesn't tell you anything, it's just there to make it easier to read multiple words strung together (since you can't say Xml parser, as you would in normal speech.)

I don't want the meaning of my pre/post fixes to be blurred by being both logical and readability separators. When I've used other languages their use for logical separation is minimal so its mostly alright (E.g. _foo in Lua for private variables; there are less than a handful of logical-separation cases, so the ambiguity isn't as bad.)

Here in C land, I will be using it a lot, so want clarity. Here's some of what I'm suggesting:

ClassName_methodName();
someStandaloneUtilFunc();

DynamicArray *array = DynamicArray_new();
DynamicArray_shrinkAndFill(array, 0, 12);
DynamicArray_doSomeFancyShtuff(array, COLOR_RED, GOOD_STUFF, 12);
DynamicArray_free(array);

With the multi-word method and class names, I feel like this makes clear the distinction between what is the class, and what is the method.

Take the following instead. Isn't it much harder to reason about?

Dynamic_array_shrink_and_fill(array, 0, 12);

DynamicArray_shrink_and_fill(array, 0, 12);

DynamicArray_shrinkAndFill(array, 0, 12);

I also occasionally have to add a post-fix for internal stuff, to help with macro magic, etc.. Example:

I'd name my function foo_base and have a macro called foo. The user would call foo as the macro pretends to be foo, it just does some syntactic sugar to the args.

Another example is foo_t for types.

Is there any reason not to do this? I feel like instinctively seeing a function name with both separators used feels like a beginner mistake, but also knowing the rationale behind the naming used makes it much easier to read. I'm definitely leaning towards using this, but want other people's opinion on it.

[1] C technically does have namespaces, but they are 4 built-in ones (one for structs/enums, one for goto labels, etc...); not ones that a program can create or modify. So not really relevant to the issue here.