|
THS 2011-2012 |
CProg /
C Syntax: Saying the Right ThingIn order for your program to compile, you must correctly use C syntax. When you make a syntax error, the compiler will give you an error message and the line number the error appears on. Sometimes the error message isn't as helpful as you would like, so it's important to remember the most basic syntax rules, as it is often the smallest error that is hardest to find. C Character SetThe C language will only use the following characters. C programs can display many other characters (for example: @ or ^), but in those situations, the special characters are just data, and cannot be translated into executable code.
C KeywordsThe following keywords are reserved for basic C operations. Each has a specific meaning or function, so when you create your own data variables and functions, make sure you do not give them the same name as a C keyword.
[1] Naming RulesWhen you are naming a variable, the first character must be an underscore or a letter. Introduce before UseWhen you use functions or variables, you have to make sure you declare them before you use them. It is best to introduce new things at the top of each file and each function. TerminationOne error that is often made by beginners is forgetting to terminate their commands. For example, here are some single lines of code terminated by semicolons: int num_of_bumps = 0; cr8_update(cr8); cr8_drive(100,DRIVE_STRAIGHT); The if, else, while, and for commands are somewhat of special cases. When you have an if statement or a loop with the curly braces { }, it is terminated by the closing curly brace }, like below:
if(cr8->bumper_left)
{
cr8_beep_short();
cr8_delay(500);
} // This curly brace terminates the if statement
while(cr8->bumper_left == 0)
{
cr8_drive_direct(100,100);
cr8_delay(15);
cr8_update(cr8);
} // This curly brace terminates the while loop
If you don't use curly braces, an if, else, or loop will only consider the very next line of code to be associated with it. This can cause some confusion, which is why it is ussually better to use curly braces. In the example below, the two if statements look the same, but will do very different things:
// Lights up Command Module LEDs
// if a bump is detected on the left side
if(cr8->bumper_left)
{
cr8_set_mc_led0(on);
cr8_set_mc_led1(on);
}
// Lights up one Command Module LED if a
// bump is detected, always turns the other
// LED on.
if(cr8->bumper_left)
cr8_set_mc_led0(on);
cr8_set_mc_led1(on);
White SpaceGenerally, white space (tabs and spaces) is skipped over by the C compiler. It is a good idea to make use of white space to make your code neat and easy to read; if all the code is bunched together, your eyes will have to do more work to pick out the important parts and possible logic errors. << A Simple Program | Home Page | Variables >> Have a Question? Please ask below. |