A Crash Course in C Ver 2

63
A Crash Course in C For Embedded Systems Reference: Robert Hodge

description

c course

Transcript of A Crash Course in C Ver 2

Page 1: A Crash Course in C Ver 2

A Crash Course in CFor Embedded Systems

Reference: Robert Hodge

Page 2: A Crash Course in C Ver 2

What will I learn from this presentation?

A conceptual overview of CA brief introduction to soften the shock of having to learn a new languageHighlights of main points of C languageSome pointers as to what is important and what isn’t important in C when it’s used in embedded systems

Page 3: A Crash Course in C Ver 2

What will I NOT learn from this presentation?

You won’t learn everything about C, or even everything you need to finish your course workLearn how to use the IDE help facilitiesGet a good book on C – not a huge “telephone book” sized one – you’ll never have time to read itThere are commercially available “Crash Course”books on C – find oneAsk questions – lots of people know CExperiment – write little 10-line or 20-line programs to test ideas and understanding of C; see what compile does or will accept

Page 4: A Crash Course in C Ver 2

How does embedded C differ from conventional C?

Same language – used for different purposesFewer librariesFewer I/O capabilities (usually no printer, etc. attached to embedded device)More reliance on low-level facilities (absolute addresses, memory mapping requirements for code and data)Hardware-specific libraries for ports, timers, DSP facilities, etc.Sometimes non-standard keywords & #pragma’sBottom line: generally simpler than PC-based C

Page 5: A Crash Course in C Ver 2

Lexical: Source Code Conventions

Source code written in standard ASCIILines may end in LF or CR/LF, depending on host/compilerC is a free-format language, not line-orientedC preprocessor is not part of C language per se, and is line-orientedPreprocessor lines and string literals sometimes need to be continued on subsequent lines by ending the line with a backslash \ characterC source program files normally have a file name extension of .c

Page 6: A Crash Course in C Ver 2

Lexical: Whitespace

Whitespace in source code is one or more unprintable characters: space, CR, LF, HT, VT, FFOther unprintable characters are illegal outside of quotes; should not be used directly inside of quotes (use hex notation instead)Whitespace is ignored by compiler, except where needed to separate identifiers from keywords, etc.It is best to completely avoid VT and FFUse of tabs (HT) vs. spaces for indentation is a matter of taste, convenience, adherence to project standards and facilities offered by IDE.

Page 7: A Crash Course in C Ver 2

Lexical: Identifiers

Identifiers are case-sensitive: abc and ABC are different names; if is a reserved word, IF is notAllowable characters: A-Z, a-z, 0-9, _Cannot start with 0-9Sometimes $ is allowed, but generally should be avoidedUnderscores may start identifier, but some uses are reserved for special/system names; be carefulModern compilers don’t restrict identifier length; check compiler for specific limitations

Page 8: A Crash Course in C Ver 2

Lexical: Identifiers

All-capital names are generally reserved for constants (const) and #define namesInitial-capital names sometimes used as a convention for type names (typedef, struct, union)Naming styles vary by taste: threePartNamethree_part_name

Page 9: A Crash Course in C Ver 2

Lexical: Comments

A comment is equivalent to whitespace; it acts as a separator, and is otherwise ignoredC comments start with /* and end with */No spaces between / and * are allowedC comments do not nest/* this /* is */ bad */

Comments may span multiple lines:/*comment*/

Page 10: A Crash Course in C Ver 2

Lexical: Comments

Many C compilers have features borrowed from C++ compilersC++ style line-comments may be availableThese comment starts with //, ends with end of lineNot strictly ANSI-compliant language, but often usefulWhen combining /* and // comments: “whoever gets there first, gets it”

Page 11: A Crash Course in C Ver 2

Lexical: Comments

Convention to comment-out a large block of code: use preprocessor #if 0Because it’s a preprocessor block construct, it is nestableAdditional preprocessor commands discussed laterExample:#if 0

this line is commented out#endif

Page 12: A Crash Course in C Ver 2

Lexical: Integer constants

Decimal values: write without leading 0Octal values: write with leading 0077 same as decimal 63Hex values: write with leading 0x or 0X; digits higher than 9 can be a-f or A-F0xFF same as decimal 255For readability: use 0x, not 0X, and use upper case for A-Z instead of a-f

Page 13: A Crash Course in C Ver 2

Lexical: Integer constants

Integer constants can be “long” or “regular” sizedLong constants have a trailing L or lExample: 1234L, 0xA5L

Readability: use L instead of l, because l (el) looks like 1 (one)Meaning of “long” depends on compiler and hardware; it may be 16, 32 or 64 bitsOn embedded systems, “long” may have other(non-standard) meanings; check the compiler’s documentation

Page 14: A Crash Course in C Ver 2

Lexical: Integer constants

Integer constants can be considered “signed”or “unsigned”Default is signedUnsigned integer constants are often used for absolute addresses in embedded systemsConstant can be made unsigned by U or u appended to value; example1234U, 0xA5U

Can be combined with long notation in any order or case: UL, LU, ul, lu, uL, etc.

Page 15: A Crash Course in C Ver 2

Lexical: Integer precision

Precision of integer constants and int data type is hardware dependent“Small” machines: int is usually 16 bits“Large” machines: int is usually 32 bits#include "limits.h" defines floating-point limitsCan use typedef keyword for user-defined types, to hide these differences (portability)

Page 16: A Crash Course in C Ver 2

Lexical: Characters

A character is enclosed in single quotes, and defines one and only one 8-bit characterA character is of data type charBackslash notation can be used to escape special characters, octal or hex valuesSee compiler documentation for complete list of special escaped values. Most common are '\n' for newline (LF) and '\t' for horizontal tab (HT)Literal backslash or quote character must be escaped

'a' '\033' '\xFF''\'' '\\'

Page 17: A Crash Course in C Ver 2

Lexical: Characters

Value of a character is an integer, equal to the collating sequence of the character in ASCIICheck compiler to see if char data type is signed or unsigned' ' numerically the same as 32 (0x20)'1' numerically the same as 49 (0x31)

Page 18: A Crash Course in C Ver 2

Lexical: Unicode Characters

Unicode is 16-bit character setData type is wchar_twchar_t usually a synonym for unsigned short int

Notation is L'x'Limited usage in embedded systems

Page 19: A Crash Course in C Ver 2

Lexical: Strings

Strings are zero or more ASCII characters enclosed in double quotesStrings are of data type char * (pointer to character)"Hello, World"

C compiler automatically adds a binary-zero character at the end of a string literal in memoryThis zero-byte is called the null terminatorStrings have limited use in embedded systems

Page 20: A Crash Course in C Ver 2

Lexical: Strings

The value of a string is a pointer, a memory addressA string of length one is not a character'x' is not the same as "X"

Escaped characters in strings – basically use same rules as for char values

Page 21: A Crash Course in C Ver 2

Lexical: String Continuation

A string too long to fit on one line can be written on multiple linesStandard C method: use backslash on one line, continue string in column 1 of next linestr = "Hello, \World";

ANSI C and C++ method: “pieces” of string are concatenated at compile time, without backslashstr = "Hello, ""World";

Page 22: A Crash Course in C Ver 2

Lexical: Floating-Point Values

Floating-point values in C are much like other languagesRequires a decimal point and/or an exponent to distinguish from integerExponent format is [+|-] [E|e] expon#include "float.h" defines floating-point limitsExamples:123.0 0.123 .123 123. 1E5 2.3e-4

Page 23: A Crash Course in C Ver 2

Lexical: Floating-Point Values

Floating-point literals default to type double (64-bit IEEE format)Can force a value to type float (32-bit IEEE format) by F or f suffixCan explicitly label a value as double by D or d suffixCompiler can convert between float and doublein expressions and in function parameters; choice depends on application, available memory, etc.Examples:123.4F 123.4d

Page 24: A Crash Course in C Ver 2

Lexical: Arithmetic Operators

Usual: + - * / < <= > >=Modulus (remainder): %Equal to, not equal to: == !=Shifts: << >>Logical and, or, not: && || !Bitwise AND, OR, NOT, XOR: & | ~ ^Address-of: unary &Pointer dereference: unary *Pointer qualifier: ->Struct/union member qualifier: .

Page 25: A Crash Course in C Ver 2

Lexical: Assignment Operators

Usual: = used to assign to variablesAssignment is an operator, not a statement.There is no assignment statement, only an assignment expression, in C; multiple assignment goes right to left: a = b = c;Compound assignments perform arithmetic and assign; a shorthand notationExample (equivalent assignments)a = a + b;a += b;

Available compound operators:+= -= *= /= %= <<= >>= &= |= ^=

Page 26: A Crash Course in C Ver 2

Lexical: Increment/Decrement Operators

Increment, decrement: ++ --These operators have side effects: they change a variable in memory and produce a value resultSomewhat like compound operators += and -=Example: x++; /* add 1 to x */Two formats: prefix and postfixPrefix format: ++x; first increments or decrements a value by 1, then uses newly modified value in rest of expressionPostfix format: x++; uses old value in expression, then increments or decrements the value by 1 later

Page 27: A Crash Course in C Ver 2

Lexical: Increment/Decrement Operators

Example:int x1=10, x2=20, x3=30, x4=40, y;y = ++x1; // y == 11, x1 == 11y = x2++; // y == 20, x2 == 21y = --x3; // y == 29, x3 == 29y = x4--; // y == 40, x4 == 39

Page 28: A Crash Course in C Ver 2

Lexical: Comma Operator

Also called the sequential evaluation operatorUsed where multiple expressions (possibly with side-effects) must be used where one expression is expectedOften seen in for loopsDo not use comma to separate subscripts in multi-dimensional arrays - it won’t work. Be careful!Example:x = (y=1),(z=2); // y==1, x==2, z==2

Page 29: A Crash Course in C Ver 2

Lexical: Conditional Operator

Also called a tertiary operator or ?: operatorA compound format, used as a short-hand to avoid using an if statementFormat:a = b ? c : d;

Meaning: if b is considered true, then a=c is performed, else a=dRecommendations: Don’t overuse this syntax; use parentheses; think twice before nesting them; consider readability before using and while writing such expressions

Page 30: A Crash Course in C Ver 2

Data Type names: built-in

char: 8-bit integer (!) value; may be signed or unsigned (check your compiler); can be used for small values or characters

short: usually 16-bit valueint: usually 16-bit on embedded systems, and 32-bit

on Windows PC-based Clong: usually 32-bit valuefloat: usually 32-bit (single) IEEE floating-pointdouble: usually 64-bit (single) IEEE floating-point

Page 31: A Crash Course in C Ver 2

Data type precision and typedef

There is no standard precision for char, short, int and longOnly absolute guarantee on sizes:char ≤ short ≤ int ≤ long

When precision is critical, use typedef to define a user-defined type having a precision you need, while keep the code portableExample: I need a 32-bit (4-byte) integer type, and the compiler's long type has ittypedef long int4;

Page 32: A Crash Course in C Ver 2

Data type modifiersunsigned: use entire precision of variable without a sign bit; used with addresses and sometimes with charactersstatic: variable is allocated in memory at compile time, not at run timeextern: variable is allocated in another source file, or in a separately compiled function libraryModifiers are often combined with typedefExamples:unsigned char a;static int b = 2;extern long c;typedef unsigned int uint;uint d; // same as: unsigned int d;

Page 33: A Crash Course in C Ver 2

Data type void

void is not an actual data typemain uses of void

the return-type of a function that doesn’t return any valuethe type of a pointer not associated with any particular data type; often used with memory management functions

Examples:void main() {} // main does not return a valuevoid *buffer; // buffer points to memory of unknown type

Page 34: A Crash Course in C Ver 2

Program Structure: declarations and definitions

A C program consists of one or more “external declarations”.A declaration is a C statement that describes a function or variable that is defined elsewhereA definition is a C statement that allocates storage for a variable, or creates executable code for a function, at the point the definition appearsA definition acts as its own declaration, but not vice-versaC makes a big deal out of declaration vs. definition, so it’s important you understand the distinction

Page 35: A Crash Course in C Ver 2

Program Structure: externals

External declarations have an ‘external’ attribute associated with themSometimes the external attribute is implied by the language and by usage; in other cases, the C keyword extern is requiredExternal declarations common to multiple source files (in a modular program) should be included in a header file (#include "abc.h") to keep the definitions consistentAs a rule (but it’s not a law), we usually don’t put definitions in header files

Page 36: A Crash Course in C Ver 2

Program Structure: Example

#include <stdio.h>char msg[] = "Embedded Systems";void main(){

printf ("Hello, %s World\n", msg);}

// output: Hello, Embedded Systems World

Page 37: A Crash Course in C Ver 2

Program Structure: main()

A function called main must appear as somewhere in your program; it is the first function that executes, and defines the starting point of the programA C runtime library actually executes first, then calls main as a subroutineThe C runtime library for embedded systems is usually very different than those used on a PC-based C compilerSee hardware vendor for specifics on runtime library and main function for your embedded system

Page 38: A Crash Course in C Ver 2

Preprocessor: Basics

The C compiler has a preprocessor, which uses directives embedded in your C program, to insert additional C code, to selectively incorporate and/or exclude code, and to selectively modify codeThe resultant effective program is what is actually compiledYour source program is never actually changedOld days: preprocessor actually created an intermediate file which was then compiledNow: preprocessor is integrated; creation of intermediate file is done internally in one passAll preprocessor directives start with #

Page 39: A Crash Course in C Ver 2

Preprocessor: #include

#include copies files from an include library, which are compiled as if the contents of the file were actually part of your programIncluded files are often referred to as header files, since they usually appear at the head (the beginning) of your programHeader files normally have a file extension of .h, but can have any valid file nameExamples:#include <stdio.h>#include "myfile.h"

Page 40: A Crash Course in C Ver 2

Preprocessor: #include

Compiler looks for included files using an include pathPath usually defined by INCLUDE environment variable or by IDETwo kinds of include – different search orderFile name "abc.h" – search local directory first, then the include pathFile name <abc.h> - only search include path; normally used for system include files

Page 41: A Crash Course in C Ver 2

Preprocessor: #include

Commonly used system include files<stdio.h> // standard I/O definitions<stdlib.h> // standard function library<math.h> // math functions<ctype.h> // character classification<string.h> // string handling functions<assert.h> // defines assert() macro<malloc.h> // memory allocation functions<time.h> // time functions

Page 42: A Crash Course in C Ver 2

Preprocessor: #define

Used for substituting a symbol with a text valueNever use constants in code, use #define to define constants with appropriate names.The name introduced in this way is often called a define name or a pound-define nameDefinition may be a simple symbol or a parameterized –this is often called a macro, a define macro or a pound-define macroLong values may be continued on multiple lines using backslash as continuationOnly name and value are used; no = or ; requiredExamples:#define PORT 0x100#define NEG(x) (-x)

Page 43: A Crash Course in C Ver 2

Preprocessor: #define

Rules and guidelinesDefine names traditionally are written in UPPER CASE; this is a convention, but not a requirementFor macros, no spaces allowed between name and parameter list, or inside the listIf a name is already defined, defining it again is a warning or error conditionA definition with no value is OK; it just makes a name known to be “defined” to the compiler

#define TEST_MODEIt is possible to remove a definition of ABC using

#undef ABC

Page 44: A Crash Course in C Ver 2

Preprocessor: #define

Traditional uses for #define:Definitions of constantsName substitution for variables and functionsDefinitions of flags to control compile using #ifSelective debugging

Examples:#define PORT 0x100#define MYFUNCTION your_function#define SUM(x,y) (x+y)#define DEBUG_MODE

Page 45: A Crash Course in C Ver 2

Preprocessor: #define

Defined names can also be introduced by command-line or through IDE

They appear to C program exactly like a name defined using #define directive

This is often done to set up compile-time optionsTypical format:cc –DNAME=value myprogram.c

Compiler has list of predefined names, like __DATE__, __TIME__, __LINE__, __FILE__

See compiler documentation for details

Page 46: A Crash Course in C Ver 2

Preprocessor: #if / #endif blocks

Defines a block of code to be included if a constant expression is true#elif and #else are optional; #endif is required#if blocks are nestable#if const_expr1// code used if const_expr1 is true

#elif cond2// code used if const_expr2 is true

#else// code used if const_expr 1 and 2 // are both false

#endif

Page 47: A Crash Course in C Ver 2

Preprocessor: #ifdef, #ifndef, defined(x)

To select code if a name is defined:#ifdef ABC

To select code if a name is not defined:#ifndef ABCdefined(x) test can be used to test multiple names and more complex tests:

#if defined(ABC) && (!defined(DEF))

Page 48: A Crash Course in C Ver 2

Preprocessor: #pragma

Short for ‘pragmatic comment’Used to define vendor-specific compiler optionsTypical use in embedded systems: memory load addresses for functions and static data (passed to linker)See compiler documentation for details

Page 49: A Crash Course in C Ver 2

Preprocessor: Additional directives

#line specifies line number and file name; used in C code generated by other software#error displays an error message and is treated like a compile error (compilation will be unsuccessful)

Page 50: A Crash Course in C Ver 2

Functions: (Fundamental Unit of C Program)Only one function is named as main function. When program is executed its starts its execution with main function.Regarding functions one should clearly differentiate the following:1) Function Prototype 2) Function Definition 3) Function invocation or calling a Function.

• Function prototype is also called function declaration or function signature. Prototype tells us the return value type of a function, number of parameters of the function and the parameter types.

• Function definition is the one, which contains the implementation of the function.

• Function invocation is nothing but the calling of a function.

Page 51: A Crash Course in C Ver 2

“ return “ statement and control flow in a functionThe return statement in a function serves two purposes, one is to return a value to the calling function. Second one is to exit from the function, from in between the function. If function is a void function, then no return statement is required. Function automatically returns once it reaches end of the function.

Function parameters, Pass by Value and Pass by referenceIn C by default parameters are passed by value only. If you want to pass by reference of a variable, you have to do it explicitly by using ‘&’ operator.

Input parameters and Output parameters of a functionTypically a function accepts all its input through the parameters. So these parameters are called input parameters. In general if a function wants to output a value to the calling function, then we can return a value through the return statement. But if the function wants to return more than one value to the calling function, then we will use output parameters. Output parameters are passed by reference using ‘&’ operator. Because of the reference the function can place the output value in the variable, whose reference is given in the output parameter. Eg. Void areaOfTriangle(int base, int height, int *area) has two input parameters and one output parameter.

Page 52: A Crash Course in C Ver 2

Function pointersPointer variables can be used to store addresses of functions. These pointer are called function pointers. Function pointers are useful to implement callback function mechanism, used in event driven programming.

Using a given functionusing a already available function also requires good skills. First you should understand the interface (or prototype) of that function well, so that you can pass parameters correctly. If function is returning some value , you should use it. Most of the functions return the status as return value. Typical tendency of a programmer is to ignore the return value.Normally using of other function will happen in two cases

1) Using library functions.( stdio ) 2) Using functions of other module being developed by other

members .The second one requires more care. As library functions will be more tested they do not require typical checks for validating the pointer variables for non null value, and also checking the limits of the parameters.

Page 53: A Crash Course in C Ver 2

Reentrant function:Reentrant function is usable by the several tasks and routines synchronously (at the same time). This is because all its argument values are retrievable from the stack. A function is called reentrant function when the following three conditions are satisfied.1) All the arguments pass the values and none of the argument is a pointer whenever a calling function calls that function.2) When an operation is not atomic, that function should not operate on any variable, which is declared outside the function or which an interrupt service routine uses or which is a global variable but passed by reference and not passed by value as an argument into the function.3)That function does not call any other function that is not itself Reentrant.

Macros and functionsFunctions are used when the requirement is that the codes should be compiled once only. However , on calling a function, the processor hat to save the context, and return, restore the context (Toverheads). Further, a function may return nothing or return a Boolean integer or any primitive or reference type of data. Macros are used when short functional codes are to be inserted in a number of places or in functions.We use function when the Toverheads << Texec

and a macro is used when Toverheads ~= or > Texec

Page 54: A Crash Course in C Ver 2

Pointers:Concept of Address and SizeIn a program, every variable and function will have unique address associated with it. Whenever a program is loaded into the memory for executing, the variables and functions and functions will be loaded into their respective addresses.Besides the address, every variable will also have size. Same way every function will occupy some space in the memory.

Direct Addressing:Whenever any variable is defined, some memory will be allocated for that variable. The address of this memory is the address of this variable, the value will be placed in the memory location of its address. This is called direct addressing. int a ;/** memory allocated say at address 100**/a = 12 ;/**a value 12 will be placed in memory starting at address 100**/

Page 55: A Crash Course in C Ver 2

Pointer variables and indirect addressingPointer variables are used to store addresses. Pointer variables provide indirect addressing capability.int *p ;/** memory allocated for p at some address **/p = 500 ;/** direct addressing: 500 is placed in p’s memory **/*p = 12 ;/**indirect addressing: A value of 12 is placed in memory location,

whose address is present in p’s location. That is 500. So 12 will be placed in memory location 500**/

Indirect addressing is also called pointer dereferencing.p = 1000;*p = 12; /This time 12 will be placed in memory location 1000*/Indirect addressing provides the capability to read from any memory location of our interest . Which ever memory we would like to read or write, we can initialize pointer variable ’p’ with the address of that memory. Now by dereferencing the pointer we can read or write into that memory location.

Page 56: A Crash Course in C Ver 2

Pointer Dereference:Putting * in front of a pointer variable and using is called dereferencing. When you dereference a pointer variable, it represents variable of that pointer type.

float *pf ;Compiler understands two things. One is ‘pf’ is a pointer variable. So memory space will be allocated to this pointer variable. Second is that when you dereference this ‘pf’ pointer it acts as float variables. So *pf is a float variable.Dereferencing of pointer variable provides the indirect addressing capability.

Pointer Type:Every pointer variable will have a type.int *pi; // pointer of type integershort *ps; //pointer of type shortchar *pc; //pointer of type char

Page 57: A Crash Course in C Ver 2

Using Pointer as arrayDe-referencing is the power capability of pointers. We can de-reference not only objects pointed by a pointer, but also the successive objects.*p is the object pointed by pointer p.*(p+1) is the second object from the object pointed by pointer p.*(p+2) is the second object from the object pointed by pointer p.The same dereferencing can be achieved by using the pointer as array.p[0] ; object pointed by pointer pp[1] ; second object; p[2] ; third object;

Use of pointers:• For accessing absolute memory of our interest.• Accessing memory belonging to one type as different type.• Pointer provide ‘pass by reference’ method for functions• Dynamic memory• Linked lists• Function pointers for Call back functions or event handlers

Page 58: A Crash Course in C Ver 2

Arrays and StructuresArrays and structures are the basic building blocks of data structures. Variables can

be classified into scalar, vector and compound. Normal variables char, int float as of type scalar. The arrays are considered as vector type and structures represent the compound type.

Arrays:We use arrays when we need multiple elements of same type. These elements of an array could be simple variables like chars and integers or could be structures also. These structures may contain arrays within themselves. In this way we can build complex data structures with the help of arrays and structures.we can get address of any element of array by using ‘&’ operator &arr[1] //*address of second element of array *//

&arr[2] //*address of third element of array *//

Page 59: A Crash Course in C Ver 2

Passing arrays to functionsAs array names represent pointers. We can pass arrays to a function as pointers.eg. Void dispMarks(int marks[]);

Void dispMarks(int *marks);Both the examples can be used to declare a function which takes marks array as parameter. Notice pointer and arrays can be used interchangeably.StructuresOrganizing the information as structures or objectsIt is a good practice to organize all the global data as structures or as array of structures . It is not good to have so many global scalar variables. Organizing all the global data into a set of structures provides modularity to the data. In fact we can equate objects in object oriented programming to structures in C programming. So similar to how object oriented programmers try to identify the objects. C programmers should identify the good structures and build functions to operate on these global structures.eg: typedef struct (defining a graphic point structure, which contains

{ int x x and y c-oordinate fields.)int y

}point_t;point_t point;

Page 60: A Crash Course in C Ver 2

Structure pointersUnlike arrays, name of a structure does not represent a pointer. Structure variable behave like normal scalar variables (int, char..). So to get the address of a structure we should use ‘&’ operator. sampStruct_t st; /* structure variable */sampStruct_t pSt; /* pointer to structure variable */

pSt = &st; /* pointer is initialized with the address of ‘st’ */

The way we represent fields of a structure is different for structure variables and structure pointers.st.chVal; /* we use (.) To separate structure variable name and field name*/st.inVal;pSt chVal; /* we use arrow to access fields through structure pointer */

In fact the above is the shorthand notation for (*pSt).chVal.

Page 61: A Crash Course in C Ver 2

Self referential structuresIf a structure contains, pointer to itself as an element in the structure, it is called self referential structure. Self referential structures are the best way of implementing the linked list. As each node in the linked list point to the identical node, so node structure should contain a pointer to the same structure.eg: typedef struct studentNode_s

{char name[20];int stuIdint phoneNum;struct studentNode_s *pNext;

} studentNode_t;

Passing structures to functions as parametersStructure variables, when passed to a function, they will be passed by value similar to normal variables. If structure is big, passing it by value is not efficient mechanism, as entire structure needs to be copied to the stack. Better way to pass structure is by reference, by using ‘&’ operator.eg: displayStructure(st1) ; /* structure is passed by value */

displayStructure(&st1) ; /* structure is passed by reference */

Page 62: A Crash Course in C Ver 2

Optimization of Memory needs1) Byte arithmetic takes less time than integer arithmetic. So use unsigned

bytes for short and a short for integer if possible, to optimize use of RAM and ROM available in the system.

2) Avoid use of library functions in case a generalized function is expected to take more memory when its coding is simple.

3) Use modifier ‘register’ for frequently used variables.4) Use global variables if shared data problems are tackled and use static

variables in case frequently saving on the stack is needed. ( when a variable is declared static, the processor accesses with less instructions than for the stack).

5) Whenever feasible combine two function of more or less similar codes.6) Reduce use of frequent function calls and nested call and thus reduce the

time and RAM memory needed for the stacks.7) Use the delete function when there is no longer a need for a set of

statements after they execute.8) If feasible use alternatives to switch statements with a table of pointers to

the functions.

Page 63: A Crash Course in C Ver 2

Useful links:

Quality and Standards (automotive):http://www.misra-c2.com/ (look in resources)

Cosmic compilers:http://www.cosmic-software.com/download.php

Developing Embedded Software in C:http://www.ece.utexas.edu/~valvano/embed/toc1.htm