NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
Sensors, Actuators, and Robotics » C Coding Best Practices
August 10, 2012 by Medic8388 |
Hey guys,
Im a vb.net programmer by day and Ill have to say this is a whole different ballgame and Im loving it. Now that being said when Im making an application or report for work I organize my code into modules or classes. One of the things Ive noticed with these C programs is the subroutines and functions are at the top and main{} is at the bottom (this is opposite to the way I organize my code) and was wondering why its done that way. Going into this I have been previously "exposed" to C++ but since at work I use vb.net thats where most of my learning has been recently. Any advice for "thinking like a c program" compared to "thinking like a vb.net program"? |
---|---|
August 10, 2012 by Medic8388 |
Dont know why I posted this in here... can it be moved? |
August 10, 2012 by Ralphxyz |
Hi Medic8388, you can just repost in the Microcontroller thread! I believe your functions can go any where outside of main { }. But some programmer will probable jump in, hopefully. Ralph |
August 10, 2012 by pcbolt |
Medic - The reason the functions and subroutines are above "main()" is because it basically kills two birds with one stone. You can put a subroutine that is called in "main()" at the bottom of your code listing but then you would have to declare a "function prototype" above the "main()" portion of the code. A "function prototype" is different from the function code itself. The prototype tells the compiler HOW to jump to a subroutine by telling it what type of variable to return (if any), the name of the subroutine and the number and types of variables used when the subroutine is called. Here is a subroutine definition:
To declare a prototype for this subroutine, you'd use:
(You don't have to put in the names of the passed variables, but it helps understand the code better.) If the code definition is above "main()" you do not have to do this. You can also put the prototype in a separate header file (i.e. "my_functions.h") as long as you put the header file name in amongst the other "includes" at the top of most program listings. If you take a look at the source code and header files for say "lcd.c/lcd.h" in the "libnerdkits" directory, you'll see all of this in action. |
August 13, 2012 by BobaMosfet |
The short answer is because of historical and symbol-table reasons during compilation. Having everything neatly declared and defined prior to use was a requirement originally. You should always use prototypes (as C is a non-overloading language) to ensure all calls are grammatically correct. Mileage today varies based on whatever compiler you're using, currently. BM |
Please log in to post a reply.
Did you know that you can aim and fire a servo-controlled water gun from your computer? Learn more...
|