32
C-Fundamentals V12.docx 1 of 32 VARIABLES: Variables are created by specifying a type and a name for the quantity you would like to store. Choose a type that fits what you are trying to store that’s the proper size to hold the minimum and maximum possible values. Choose a name that is descriptive. DO not use names like: var, var1, var2. They are not descriptive and only confuse! Some examples:

VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

  • Upload
    vominh

  • View
    221

  • Download
    2

Embed Size (px)

Citation preview

Page 1: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 1 of 32

VARIABLES:

Variables are created by specifying a type and a name for the quantity you would like to store. Choose a type that fits what you are trying to store that’s the proper size to hold the minimum and maximum possible values. Choose a name that is descriptive. DO not use names like: var, var1, var2. They are not descriptive and only confuse!

Some examples:

Page 2: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 2 of 32

LIMITS for standard variable types:

The following output was generated by the application 2.3_5270_Limits which explores the name, storage size, and max and min values associated with the basic and floating point types. This project is included as an Eclipse project with Lesson 2. In addition to the limits for each type, the project demonstrates how to output and format these numeric types with the iprintf() and printf() functions.

Page 3: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 3 of 32

HOW NUMBERS AND CHARACTERS ARE STORED.

Computers read inputs, manipulate data, and create outputs. However, before we can learn about the functions that carry out those activities, we’ll need to understand how numbers and characters are represented and stored in computers. The following sections address this.

NUMBER REPRESENTATIONS: decimal, hex and binary notation:

DECIMAL CONSTANTS: — start with a non-zero number:

26

HEXADECIMAL CONSTANTS: — start with 0x or 0X: 0x1A // Same as 26 decimal

BINARY CONSTANTS: — start with 0b: 0b00011010 // Same as 26 decimal

One way to do conversions is to use the Windows calculator: ..\Start Menu\Programs\Accessories\Calculator. Use the view menu to select PROGRAMMER mode. Select the DECIMAL mode, enter a value, and then use the radio buttons to convert it to HEX or BINARY. You can also use the AND / OR/ XOR / NOT and other logical operators to see the results of these operators on two operands.

But let’s examine how to do Decimal / Hex / Binary conversions manually. When we’re done we’ll have a new perspective on what each digit and digit-position means and why they matter. From the last section on Limits, we saw that an UNSIGNED CHAR takes one BYTE of memory and can hold a number from 0 to 255 decimal. As we’ll see, to store the number 255, each of the 8 bits in the byte are set. Here’s why.

Page 4: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 4 of 32

When we write the number 255, we implicitly use decimal notation, ie base 10. Base 10 means there are ten choices for each digit, so each digit can range from 0 to 9. You remember the units, tens, and hundreds columns from grade school. What we’re saying when we write 255 is:

(2 x 100) + (5 x 10) + (5 x 1) = 255

We could also write this using exponential notation:

Hundreds Tens Units (2 x 102) + (5 x 101) + (5 x 100) = 255 (Remember, 100 = 1

In other words, each column (right to left) is an increasing power of 10. When we say our numbers are “base 10” or “decimal notation”, that’s why: because the columns are powers of ten. This in turn means that there are ten choices for each digit.

HEX NOTATION

Let’s try to write a number with a value of decimal 12 in hexadecimal, or “hex” notation. Hex notation is base 16. This means each digit has 16 choices: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F where the first ten digits ( 0 -- 9) are the same as for base 10, and “A” through “F” represent the 6 new digit choices. In other words, single-digit hex numbers can range from 0 to F. As a signal about what base we’re using, hex numbers are usually preceded by “0x” or “0X”. Let’s try some conversions:

Decimal 9 = 0x9 (Same number in both bases)

Decimal 10 = 0xA

Decimal 15 = 0xF

If we want to add one to 0xF (decimal 15), we’ll need to “carry” and the hex result would be:

0x10 = (1 x 161) + (0 x 160) = 16 decimal

Try finding the decimal equivalent of the hex number 0xB23F:

(0xB * 163) + (0x2 * 162) + (0x3 * 161) + (0xF * 160) =

(11 * 163) + (2 * 162) + (3 * 161) + (15 * 160) =

(11 * 4096) + (2 * 256) + (3 * 16) + (15 * 1) = 45,631 decimal

BINARY NOTATION: bits and bytes

Binary notation is the same concept as decimal or hex notation except the base is 2. Therefore there are only two choices for each digit: 0 or 1. Each digit position is a power of the base, ie a power of two:

These digit positions are called bits. In computer applications, binary notation is important because the 1 correlates to the presence of a charge, a voltage that is ON, or a “logic high” voltage, while the 0 correlates to the absence of charge, a voltage that is OFF, or a “logic-low” voltage. Memory locations composed of 8 bits (called bytes) store the state of charge for 8 transistors, or, alternatively, as the ON/OFF state of 8 transistor switches, or of 8 sequential pieces of information, each high or low, or TRUE or FALSE.

Page 5: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 5 of 32

Finally, try evaluating what happens when all 8 bits in a byte are set. If all bits are set, the memory location has no more room to store any additional information. This is why a byte can hold any value from 0 to 255. This is the concept underlying the Limits Project described above.

A CONVERSION TABLE for the first 16 digits:

DECIMAL BINARY HEX DECIMAL BINARY HEX

0 0 0 8 1000 8

1 1 1 9 1001 9

2 10 2 10 1010 A

3 11 3 11 1011 B

4 100 4 12 1100 C

5 101 5 13 1101 D

6 110 6 14 1110 E

7 111 7 15 1111 F

Page 6: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 6 of 32

CHARACTER REPRESENTATIONS: ASCII notation:

For historical reasons, most characters are stored on computers in a format based on or derived from ASCII codes. ASCII stands for American Standard Code for Information Interchange. ASCII codes were developed by Bell Labs in the 1960s as a numerical representation for the letters and characters used to send what amounts to an early form of text messages between teletypes. The first 32 ASCII codes represent non-printing characters that are now rarely used for their original purposes. The remaining 96 ASCII codes encode some simple symbols and punctuation, and the basic ‘0-9’, ‘A-Z’, and ‘a-z’ characters. Although there are now “extended,” or “unicode” (UTF) character sets that encode a much wider range of characters, for basic programming purposes, most characters remain encoded via ASCII. Additionally, many programs, for example Microsoft Word create data files that store information about the format of characters. Nevertheless, these programs can often save “raw text files,” and these files are simply files that sequentially list the ASCII characters in a block of text.

Page 7: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 7 of 32

ASCII Codes:

EOL end of line sequences

Windows end of line sequence: \r\n Unix end of line sequence: \n Mac end of line sequence: \r

Common ASCII codes to know

Char Dec Oct Hex What Are They ----------------------------------------------------------------------------------------- (nul) 0 0000 0x00 Null (ht) 9 0011 0x09 Horizontal Tab (nl) 10 0012 0x0a New Line (vt) 11 0013 0x0b Vertical Tab (cr) 13 0015 0x0d Carriage Return (sp) 32 0040 0x20 Space 0 48 0060 0x30 zero A 65 0101 0x41 capital A a 97 0141 0x61 lowercase a

ASCII codes and their escape sequences

ASCII Name Description C Escape Sequence ----------------------------------------------------------------------------------------- nul null byte (zero) \0 bel belcharacter \a bs backspace \b ht horizontal tab \t np formfeed \f nl newline \n cr carriage return \r

Page 8: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 8 of 32

CREATING FUNCTIONS

(Please read Page 96 – 106 in C in a Nutshell for more detail about functions).

All instructions to the target CPU in C or C++ are held in functions. Each function performs a specific task or job, and is defined once. Functions are called from other functions in order to execute the implemented task.

Functions have two parts

a) a declaration (sometimes called a function prototype,) and b) a definition

See page 158 in C in a Nutshell for more detail about definitions and declarations.

A DECLARATION tells the compiler the number, type and order of the arguments a function requires for

inputs, and the type of its output. A function’s type is the type of its output. A function can only have one output parameter (one type), but it may have many input parameters. A function with no output is said to be of type void. A function that requires no inputs should be defined and declared with the key word void as the input parameter. A function declaration may optionally include the named variables that will be used in the definition, but these are for clarification only and are not required although including them is considered good practice. A function’s declaration serves as the definition if it includes a function block, or assigns a value to memory.

A DEFINITON conforms to the declaration's argument lists and implements the functionality desired by

the programmer. An object is a definition if it allocates storage. If an object or variable is initialized, it is a definition. There must be only one definition for each function.

A function DECLARATION is required when a function, variable or other object is called before its definition, or in a different file.

DECLARATIONS allow the compiler (and users) to understand the input and output arguments. The number, type and order of the arguments must be the same in the DECLARATION, the DEFINITION, and finally in the FUNCTION CALL. If not, a compiler error will be generated.

Page 9: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 9 of 32

SEPARATE COMPILATION An important feature of C and C++ is the ability to modularize code. This typically results in

the following program organization: • A source file with the suffix “.c” or “.cpp” that contains definitions for a module’s

functions, let’s call it ModuleASource.cpp • A header file with the “.h” suffix that contains declarations to tell other modules

what to expect in the related source file. It will be called: ModuleASource.h. And finally,

• A second source file, for example ModuleBSource.cpp containing functions that call the Module A’s functions. This second source file is informed about Module A’s functions by calling either:

#include “ModuleASource.h” // if ModuleASource.h &.cpp // are in your project, or #include <ModuleBSource.h> // if ModuleBSource.h &.cpp // are system files.

Page 10: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 10 of 32

Header files contain: • symbolic constants created with the key words #define, or const, • typedefs: declarations that a new name create a new type • variables • uC/OS objets: Semaphores, Mailboxes, Fifos, Queues, and Flags • variable declarations, • structure declarations // no assignment, just the pattern for the struct • class declarations, • template declarations, • inline functions • function declarations (also called function prototypes), • extern declarations where the keyword extern publishes objects defined

elsewhere (typically in the corresponding .cpp file) to make them accessible globally. For example:

extern Byte MyLEDMask; // Adding the "extern" keyword

// essentially publishes the variable // named MyLEDmask so it can be recognized globally. // Without the "extern" modifier, this expression would // be just a simple declaration to make MyLEDmask known // throughout the corresponding .cpp file matching // the .h file.

• guard directives: to insure the .h file is included only once. #ifndef READSW_H_ #define READSW_H_ // Your code here #endif /*READSW_H_*/

• Headers should NEVER contain definitions.

Source files contain: • Variable definitions and assignments • Function definitions

Page 11: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 11 of 32

EXPRESSIONS:

TRUE is defined as non-zero.

FALSE is defined as zero.

Expressions end with a semicolon. y = x; sum = Num1 + Num2; iprintf(“Hello”); y < x; // OK, but not useful getchar(); // Explicitly discard the return value

BLOCKS are compound expressions between braces: { // Declarations, Block #1 int x=0; int y=0; int i=0, j=1; static long status = 0; sum = x + y + 27; // Statement if(status == 0) // A 2nd block { int i = 2; } }

Page 12: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 12 of 32

OPERATORS: The following table is copied from Page 59 in C in a Nutshell. It illustrates the standard operators used to build expressions. In particular, please understand that BITWISE operators like “|” or “&” (OR, then AND respectively) work on individual bits, whereas LOGICAL operators like “II” or “&&” (OR, then AND respectively) work on the operand as a whole. For example:

BYTE LEDmaskA = 0x03; BYTE LEDmaskB = 0; // BIT-WISE OR uses the | symbol: BYTE LEDmaskC = LEDmaskA | LEDmaskB; // LEDmaskC = 0x03 // LOGICAL OR uses the || symbol: BYTE LEDmaskD = LEDmaskA || LEDmaskB; // LEDmaskD = 0x01, (IE TRUE)

Associativity comes in to play when two operators have the same precedence. For example, the * and / operators both have the same precedence. In that case, their associativity tells us expressions are grouped from left to right. Therefore: A * B / C evaluates to: (A * B) / C. In practice, if in doubt, add parentheses explicitly to you code to avoid misconceptions.

Table 5-4 Operator Precedence and Associativity from C in a Nutshell by Peter Prinz and Tony Crawford

Page 13: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 13 of 32

CONTROL STATEMENTS: if, if/else, while, for, do…while:

BRANCHING : if Statements if statements evaluate a condition. If the condition evaluates to TRUE, the statements in the

following BLOCK execute. The condition can be simple: if (TRUE) { DoThis(); } or can evaluate a simple statement: if (VarX == 27) {...} // IE: “if VarX is equivalent to 27”

// NB!!! DO NOT WRITE: “if (VarX = 27)” // or you will assign VarX the value of 27 // which will always be TRUE and so you // will always execute the block following the IF. or can evaluate the return value of a function, in this case where MyFunction() returns a TRUE

or FALSE value: if ( MyFunction() ) {...} Note that when either the DoThis() function, or the MyFunction() functions are called in the examples above, that parentheses follow the function name. We’ll discuss this more later, but in general, when you call a function, be sure that the function name is followed by parentheses. These parentheses deliver the argument list. In these two examples, since both argument lists are empty, we know the functions don’t require any inputs. However, by including the parentheses, you are telling the compiler to execute the function. If you did not include the parentheses, you would be telling the compiler to deliver the address where the function is stored and you’d get an unexpected result.

Page 14: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 14 of 32

BRANCHING (continued): 4 ways to write an if statement: if (condition) statement1; //one-line ---------------------------------------------------- if (condition) //No semicolon: It’s a condition, // not a statement. statement1; //One-line code, ie a statement so // it ends w/a semi-colon. -------------------------------------------------- if (condition) { //no semicolon statement1; //multi-line code between {...} statement2; } ---------------------------------------------------- if (condition) //no semicolon { statement1; //multi-line code between {...} statement2; } ----------------------------------------------------

A VERY COMMON ERROR! WRONG: if (SomeVariable = 0) //The = operators is an ASSIGNMENT. // = means Assign 0 to SomeVariable. // Therefore the condition will ALWAYS be // FALSE & Statement1 will NEVER // execute. In detail, since you statement1; // just assigned 0 to SomeVariable. // the condition evaluates to FALSE. ---------------------------------------------------- RIGHT: if (SomeVariable == 0) //The == operators is a TEST. It means: //“If SomeVariable is equivalent to 0”. statement1; // If condition is TRUE, do Statement 1.

Page 15: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 15 of 32

BRANCHING : IF/ELSE if/else statements evaluate a condition and branch one of two ways depending on the result. If

the condition evaluates to TRUE, the statements in the BLOCK following the if execute. Otherwise, if the condition evaluates to FALSE, the statements in the BLOCK following the else execute. For example:

if (TRUE){ DoThis(); //execute DoThis() if condition is TRUE } else { DoThat(); //execute DoThat() if condition is FALSE }

Four ways to write an IF/ELSE statement:

if (condition) statement1; //one statement ONLY! else (condition) statement2; //one statement ONLY! if (condition) //condition has no semicolon. statement1; //one-line code, end w/ semi-colon else (condition) //condition has no semicolon. statement2; //one-line code end w/ semi-colon if (condition) { //no semicolon statement1; //multi-line code between {...} statement2; } else { statement3; //multi-line code between {...} statement4; } if (condition) //no semicolon { statement1; //multi-line code between {...} statement2; } else { statement3; //multi-line code between {...} statement4; }

Page 16: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 16 of 32

while LOOPS: while LOOPS are top-driven statements. They’re designed for situations where the programmer

doesn’t know how many loops, (if any) will be required beforehand. They always test whether they should run1st. If the expression evaluates to TRUE, the statements in the following BLOCK execute.

while(expression) statement ---------------------------------------------------- // if expression evaluates to TRUE, execute statement

// Notice: // NO semi-colon after the expression // BUT semicolons after the statement:

while(i<3) iprintf("i = %d", i++); ---------------------------------------------------- while (expression) // expression has no semi-colon. // If expression evaluates to TRUE { // then execute the statement. // This one is a compound // statement, so it’s surrounded // by braces. statement1; statement2; } ---------------------------------------------------- while( input == 0) x++; // simple expression // to increment x while // input is FALSE. ---------------------------------------------------- while( !(input) ) x++; // equivalent expression ---------------------------------------------------- while( getchar() ) x++; // expression calls a

// function and evaluates // its return value

Page 17: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 17 of 32

while LOOP example (con’t): // Count from 1 to n… int n = 6; int i=1; while (i <= n) { iprintf(“%d “, i); // Print the decimal value of i. i = i + 1; // increment i by 1. } ---------------------------------------------------- // Count from 1 to n… Slightly more compact version int n = 6; int i=1; while (i <= n) { iprintf(“%d “, i); i += 1; // Use the += operator to add 1 to i. } ---------------------------------------------------- // A shorter, more common version… int n = 6; int i=1; while (i <= n) { iprintf(“%d “, i++); // Use ‘i++’, the ‘post-increment’ // to deliver the value of i to the // print statement, then increment // it when done. There is also a // ‘++i’ ‘pre-increment’ operator // that increments the value before // it is used. } ---------------------------------------------------- // A compound expression using a logical AND // and a function call. From the syntax, SwNotPressed // should return TRUE if NOT pressed, and FALSE if // pressed. Therefore, if the switch were pressed // the function would return with 0 and the AND // would evaluate to FALSE. The loop would // quit early if the switch were pressed: int n = 6; int i=1; while ( (i <= n) && SwNotPressed() ) { iprintf(“%d “, i++); }

Page 18: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 18 of 32

for LOOPS: for LOOPS are top-driven statements designed for counting or looping a preset, usually

predetermined number of times. A for loop does some initialization before the loop, then tests a condition. If the condition is FALSE, execution ends. If the condition is TRUE, the loop executes. After the loop executes, a step variable is incremented in a way specified in the step part of the statement. After the step, the condition is tested once again.

for (init; condition; step) { Statement1; // } ---------------------------------------------------- for (var = 0; var < max; ++var) { Statement1; // } ---------------------------------------------------- for (int var = 0; var < max; ++var) { Statement1; // }

A for loop EXAMPLE: // Count from 1 to n… int n = 6; int i=1; for (i = 1; i <= n; i++) iprintf(“%d ”, i);

Page 19: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 19 of 32

do…while LOOPS: do…while LOOPS are bottom-driven statements. They always execute AT LEAST once, even if

the expression evaluates to FALSE. After the body block executes once, the expression is evaluated. If the expression is TRUE, the statements in the body will execute again. If FALSE, the loop is over. Not as common as while or for LOOPS, Used maybe 5% of the time in situations like a keyboard

scan routine where you always want input that you will then process. do { statement1; statement2; } while (condition); //notice the semicolon! ---------------------------------------------------- do { statement1; statement2; } while (condition); //notice the semicolon! ----------------------------------------------------

A do…while EXAMPLE: // Count from 1 to n… int n = 6; int i=1; do iprintf(“%d “, i++); while (i <= n); //notice the semicolon!

Page 20: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 20 of 32

SWITCH / CASE statements

switch statements evaluate an expression and make execution jump to one of several

statements or ‘cases’. Because of this they are often called case statements. switch (expression) statement; They are often used to implement menus based on one selection from a list of options. They

may (optionally) include a default case to handle situations where none of the cases match the input.

switch (selector) { case value: statement1; break; case value: statement2; break; default: statement3; break; ---------------------------------------------------- AN EXAMPLE: switch (GetInputFromUser() ) { case ‘a’: DoAction_a(); break; case ‘b’: DoAction_b(); break; case ‘c’: case ‘C’: DoAction_c_or_C(); // do the same thing for break; // input of ‘c’ or ‘C’. default: DoDefaultAction(); // if input was not ‘a’, break; // ‘b’, ‘c’ or ‘C’ call // DoDefaultAction }

Page 21: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 21 of 32

ARRAYS Arrays store objects of a specific (but only single) type in a linear sequence. Each object is called

an element. An array is fully specified by the type, and number of its elements, for example an array of 25 type char elements. It’s fully initialized when the contents are all specified.

DEFINING ARRAYS: type ArrayName[ Number of Elements]; char ArrayOfChars[25]; // a 25 char array int ArrayOfInts[25]; // a 25 int array

INITIALIZING ARRAYS: Arrays declared with automatic storage duration are undefined. Arrays with Global or File

Scope are initialized to 0, unless they’re arrays of pointers, in which case they’re initialized to NULL.

// init 1st 6 elements w/ a, b, c, d, e, f chars: ArrayOfChars = { ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’} // init 1st 6 elements w/ the string “Hello” + “\n” // where ‘\n’ is used to mark the end of the string. ArrayOfChars = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\n’}; // init 1st 6 elements w/ the string “Hello” + “\n” // where ‘\n’ is used to mark the end of the string. ArrayOfChars = “Hello”; // Easier! //Three ways to fill first 3 elements w/ ints 0, 2, 4. // The last element’s contents depend on the storage // duration. int ArrayOfInts[4] = {0, 2, 4} ArrayOfInts[0] = 0; ArrayOfInts[1] = 2; ArrayOfInts[2] = 4; for (int = 0; i < (sizeof(ArrayOfInts) – 1) ; i++) ArrayOfInts[i] = i * 2;

Page 22: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 22 of 32

ARRAYS CHART:

Page 23: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 23 of 32

STRUCTS:

Page 24: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 24 of 32

STORAGE DURATION and SCOPE: When you define an array, (or for that matter any variable) in C the other parts of the program

that can ‘see’ it, or have access to it depend on the SCOPE or storage duration, In general, it’s best to declare and use variables and arrays where they’re used. This is called ‘block scope’ or ‘automatic duration. There are other scopes however:

int GlobalScopeArray[4]; // EXTERNAL SCOPE AVOID!!) // This array of 4 integers // can be accessed by every // function in the program. Other files that want to // access this variable often call a header file with // the following DECLARATION: // extern int GlobalScopeArray[4]; // // This tells the compiler the array’s type (int), but // also says the DEFINITION will be somewhere else. Static char FileScopeArray[4] // FILE SCOPE (BETTER) // This array of 4 chars // can be accessed by every // function in this FILE that // follows this statement. void ScopeDemo(void ) { // BLOCK SCOPE w/ automatic int SomeInts[3]; // duration (the default). // IE the array appears // and disappears // automatically when // the function’s called. // Only accessible in this // block, IE BLOCK SCOPE. static int Perm[3]; // static duration, IE // contents retained // call-to-call, but block // scope also, so Perm can // only be seen in this // function. volatile int OthersMayModify[3];// Block scope. // Volatile tells compiler to // never assume this array’s // contents. Other code, besides this // block’s code, for example an interrupt // service routine, code in another task, or // some hardware may change or modify the // contents.

static volatile int X = 3; //static & volatile //Storage allocation retained between calls. //Something outside the compiler (ISR, Task) // may change the contents. Compiler never // assumes value.

Page 25: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 25 of 32

POINTERS The simplest way to think of pointers is that they’re special variables that hold the addresses of other variables. However pointers represent not only the address of the thing they point to, but their type. For example: int MyVar = 3; // Declare an int with a value of 3. int* ipMyVar = &MyVar; // Declare a pointer-to-int called ipMyVar and

// assign it the address of MyVar. The “ip” naming convention // tells you it is a pointer-to-int. It is VERY RISKY to declare // a pointer and not assign it immediately!!!

*ipMyVar = 7; // Alter MyVar: now MyVar holds 7, instead of 3.

// To access a variable thru a pointer // you dereference it using the *. // EXCEPT in the parameter list of a declaration: // ipMyVar represents the ADDRESS. // *ipMyVar represents the VALUE // In the parameter list of a declaration the * operator is used // in conjunction with a known type, like int. For example the // following two expressions are equivalent:

int* ipMyVar // Meaning: declare a TAG of type “pointer-to-int” called ipMyVar. In other // words, ipMyVar is a pointer, and represents an address.

int *ipMyVar // Meaning: declare a TAG of type “int” called *ipMyVar. So, *ipMyVar // represents an integer value & can be used like any other int value. // Where you put the space is just a difference in emphasis. C++ is likely to use int*.

Page 26: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 26 of 32

HOW DATA IS PASSED BETWEEN C/C++ FUNCTIONS: An easy way to think about functions is to think about the TYPE of data they return: For example:

int AddTwoNums (int a, int b) { return a + b; }

This function is passed two values of type int, and it returns the sum, a single value also of type int. We’d say the function itself is of type int. Many functions do their work inside the function and return nothing. Their type is type void, for example:

void PrintSumOfTwoNums (int a, int b) { int sum = AddTwoNums(a, b); printf("sum = %d", sum) }

We’d call that function by writing:

PrintSumOfTwoNums( 2, 3);

Which would produce the following output:

sum = 5

Notice that we passed the integer values 2 and 3 to PrintSumOfTwoNums(). Inside the function we refer to those integers as ‘a‘ and ‘b‘. Next, we call AddTwoNums(a, b). When we do this, the system makes copies of the values ‘a‘ and ‘b‘ as they’re passed to the AddTwoNums() function. This is called ‘pass by value’. We know from the definition at the top of the page that the AddTwoNums () function returns a value of type int, and sure enough, we store that return value into a variable of the appropriate type, type int called sum. The statement return a + b in AddTwoNums() does the addition, makes a copy of the result, and again passes it by value out of the function where its stored in sum. By the way, when functions take no inputs, we define them with an input parameter of type void. This example also produces no return value, so its type is also void: void SayHi (void) { // no input, and no output

printf("Hi"); }

Page 27: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 27 of 32

Finally, functions may take a long list of input arguments, but they may only have ONE return type. The ‘pass by value’ technique of making a copy of the values that are passed into and out of function is the default approach in C/C++. That way, each function has its own copy of local data that helps to modularize and contain code. However, there are two other common alternatives described in the following examples. C code makes active use of pointers (which are just addresses). The functions that use pointers therefore often pass parameters using a ‘pass by address’ technique. C++ code improves readability by often using a ‘pass by reference’ technique.

PASS BY VALUE: // START of "Pass by VALUE" demo---------------------------------------------- void PBV_inner(int x) { iprintf("Start PBV_inner: original x=%d\n", x); // print value of passed in. x = 9; // modify local variable x iprintf(" End PBV_inner: changed local x=%d\n\n", x); // print it to be sure. } void PBV_outer (void) { iprintf("=============================PASS BY VALUE: \n"); int x = 1; // Declare int x & init to 1. iprintf("Start PBV_outer: x=%d\n\n", x); // print the contents of x. PBV_inner(x); // Pass x to PBV_inner iprintf(" Done PBV_outer: UNchanged real x=%d\n\n", x); // print x again. }

PASS BY VALUE OUTPUT

=============================PASS BY VALUE: Start PBV_outer: x=1

Page 28: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 28 of 32

Start PBV_inner: original x=1 // PBV_outer copied its value for End PBV_inner: changed local x=9 // x and passed it to PBV_inner // as a COPY. PBV_inner Done PBV_outer: UNchanged real x=1 // changed the value of the copy, // NOT the original x in PBV_Outer

Page 29: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 29 of 32

PASS BY ADDRESS: // START of "Pass by ADDR" demo---------------------------------------------- void PBAinner(int* px) { // Print value of pointer. iprintf("Start PBA_inner: px=%p\n", px); // We know it’s a pointer, so treat it as a pointer, IE // dereference it to show the value stored at the addr. iprintf("Start PBA_inner: *px=%d\n", *px); // Now, modify x, ( equivalent to *px) at the address given by px): *px = 9; // Verify that x changed: iprintf("Done PBA_inner changed x (using *px)=%d\n", *px); // but that pointer’s the same after the write..: iprintf("Done PBA_inner unchanged addr: px=%p\n\n", px); } void PBA_outer (void) { iprintf("=============================PASS BY ADDRESS: \n"); int x = 1; // Declare int x & init to 1. iprintf("Start PBA_outer: x=%d\n", x); // Print the contents of x. iprintf("Start PBA_outer: &x=%p\n\n", &x); // Print the address of x. PBAinner(&x); // Pass addr of x to PBAinner. iprintf("Done PBA_outer: changed x=%d\n", x); // Done: print x again. }

Page 30: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 30 of 32

PASS BY ADDRESS OUTPUT: =============================PASS BY ADDRESS: Start PBA_outer: x=1 Start PBA_outer: &x=0x20002a2c Start PBA_inner: px=0x20002a2c Start PBA_inner: *px=1 Done PBA_inner changed x (using *px)=9 Done PBA_inner unchanged addr: px=0x20002a2c

Done PBA_outer: changed x=9

Page 31: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 31 of 32

PASS BY REFERENCE: // START of "Pass by REFERENCE" demo---------------------------------------------- void PBR_inner(int& r) { iprintf("Start PBR_inner: r=%d\n", r); // Print value of the variable r references. iprintf("Start PBR_inner:&r=%p\n", &r); // Print the address of r references. r = 9; // Now, modify r, or actually modify // the contents of the variable r // references which is x. iprintf("End PBR_inner: Modified r=%d\n", r); // Verify content changed. iprintf("End PBR_inner: &r=%p\n\n", &r); // but that &r did not. } void PBR_outer (void) { iprintf("\n\n=============================PASS BY REFERENCE: \n"); int x = 1; // Declare int x & init to 1. iprintf("Start PBR_outer: x=%d\n", x); // Print the contents of x. iprintf("Start PBR_outer: &x=%p\n\n", &x); // Print the address of x. PBR_inner(x); // Looks like pass by value. // Actually pass-by-reference. iprintf("Back at PBR_outer: x=%d\n", x); // After PBR_inner, print x }

Page 32: VARIABLES: Choose a type that fits Choose a name that is ...bluewaterdesignworks.com/OCE360/LESSON_2/PDFs/1_C... · 0x1A // Same as 26 decimal . BINARY CONSTANTS: — start with 0b:

C-Fundamentals V12.docx 32 of 32

PASS BY REFERENCE OUTPUT: =============================PASS BY REFERENCE: Start PBR_outer: x=1 Start PBR_outer: &x=0x20002a2c Start PBR_inner: r=1 Start PBR_inner:&r=0x20002a2c End PBR_inner: Modified r=9 End PBR_inner: &r=0x20002a2c Back at PBR_outer: x=9