Looking for Feedback on My C Code Style
Asked by
!+Call for volunteers
Hi everyone,
I'm reaching out again because I'm eager to get some feedback on my coding style in C. I'm particularly interested in how I'm naming my variables and functions rather than the actual content of the functions themselves.
I've attached links to my GitHub repository where you can find the relevant source code:
- [style01.c](https://gist.github.com/mrEliotS/3cefe066a501c026febd3626cddbe060)
- [style01.h](https://gist.github.com/mrEliotS/50eaf44ca22b8aad2f35cb2f84a8b1db)
Please be patient with me as I'm not a native English speaker, so my grammar might be a bit off. Thanks in advance for your help!
Answers
Overall, your code looks good. Just a few points: Make sure you document any functions that allocate memory with malloc, mentioning that the caller should free it afterwards. Also, try separating concerns in your lucky number generation function; it currently mixes logic with error handling. Initialize srand once in your main function to avoid getting the same random numbers if called multiple times quickly. Returning an error code instead of just printing an error and exiting will make your functions more flexible for use in different contexts.
Reply to this answer
I noticed that the argument to your `create_lucky_num` function doesnโt seem necessary. Instead of hardcoding the size and range of numbers, think about allowing the caller to specify these parameters. Also, remember to protect your header file against multiple inclusions with `#ifndef` or `#pragma once`. It can prevent potential problems in larger projects!
9th chord: Thanks for the reminder! I'll implement those changes to improve my code structure.
Reply to this answer
How did you learn C to code like this? Any resources youโd recommend?
Natter: Hey! I mostly learned from YouTube lectures and continuously improved my style based on feedback from reviews.
Reply to this answer
Your use of camelCase for variables and snake_case for function names looks solid. However, some variable names could be clarified. For instance, instead of `luckyNum`, which sounds like a single number, consider `luckyNums` or `luckyNumList` since it represents a collection. Itโs also more common to place the `_MAX` part of a constant name at the end, so renaming `LUCKY_MAX_NUM` to something like `LUCKY_NUM_MAX` would be more conventional. For variable `swapNum`, think of using `tempNum` instead, since it represents a temporary value for swapping. You might also want to limit the scope of temporary variables to make them easier to understand. Let the names reveal their purpose clearly!
fork3ways: Thanks for the tips, I struggle with naming sometimes! I appreciate the insight on naming conventions and scope.
Reply to this answer
Add your answer
Answers are reviewed before publication.
mossy step 7: Thanks for that advice! Iโll definitely work on separating those parts and managing memory better.