Is my C upside down ?

Discussion in 'Programmer's Corner' started by TQFP44, Oct 18, 2016.

  1. TQFP44

    Thread Starter Member

    Sep 3, 2016
    Having come to C programming (PIC and XC16) from assembly and previously basic, it is easy to have possible "bad" habits when laying out code in the editor, my question relates to having the sequence of code 'areas' , ie definitions , includes , main , functions , etc does it matter , this occurred to me as my C book said , C does not need and END statement , as it uses the last brace in main(); ... all my stuff has main is at the start before the functions.
  2. joeyd999

    AAC Fanatic!

    Jun 6, 2011
    C is entirely free-form, so you can obfuscate your code to your heart's desire.

    The only caveat is that external functions and variables must be declared prior to invocation, usually by including a header file at the top of your C code.

    As you write, consider that someone else may need to read and understand your code later.
  3. dannyf

    Well-Known Member

    Sep 13, 2015
    It really doesn't matter. In a real project, most of your code will be in various .h and .c modules anyway. A typical main.c file for me contains high level logic.

    With that said, I typically write my main() towards the end of main.c, to save prototyping.
  4. MrSoftware

    Active Member

    Oct 29, 2013
    Do some googling for an explanation of the C and C++ compilation process. Understanding the various steps of compiling your C code into a binary will answer your questions about where things have to go and why.
  5. ci139


    Jul 11, 2016
    be yourself say 2 weeks / month later or after being intensively busy by something else
  6. WBahn


    Mar 31, 2012
    As with most things, there are various schools of thought. Probably the most important thing is to adopt a rational style and then use it consistently. This will not only help you code more efficiently, but will aid others that have to review/maintain your code -- even if your style doesn't resemble their style, they will be able to quickly determine what your style is and then use that to aid in interpreting your code.

    I prefer putting functions that rely on other functions later in the file. Not only does this avoid prototyping from a convenience standpoint, but it means that you can't (for functions in the same file) end up with accidental indirect recursion without the compiler at least throwing a warning.

    I also try to put into the header files only those things that are required by the code that is going to use them. This is consistent with the principle of least privilege.
  7. joeyd999

    AAC Fanatic!

    Jun 6, 2011
    That, too.