0% found this document useful (0 votes)
24 views83 pages

Embedded - C - Module1 New

Uploaded by

rahulhmr868
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views83 pages

Embedded - C - Module1 New

Uploaded by

rahulhmr868
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Embedded C Programming

Module-1: Introduction to C

Embedded C Programming Module-1: Introduction to C 1 / 62


C Programming - Overview

General purpose programming language


Developed by Dennis Ritchie
Strengths - flexibility, efficiency, widespread use
Used for embedded systems, OS, applications

Embedded C Programming Module-1: Introduction to C 2/62


Features of C Language

Structured programming approach


Direct low-level hardware access
Rich set of built-in operators and functions

Example Program:
#include <stdio.h>
int main() {
printf("Hello World \n");
return 0;
}

Embedded C Programming Module-1: Introduction to C 3/62


Introduction to Embedded C

Program for embedded devices/control, robotics etc.


Programming for microcontrollers/MCU
Tightly constrained resource usage
Low level control of hardware

Embedded C Programming Module-1: Introduction to C 4/62


Difference: C vs Embedded C

C Language: Embedded C:
High level language Tightly constrained
Large standard library No standard library
Platform independent Platform specific
Dynamic memory allocation Static allocation
Key constraints while programming for embedded systems.

Embedded C Programming Module-1: Introduction to C 5/62


Basic C Program Structure
Structure:
1 Include necessary header #include <stdio.h>
files // Declare global variables
int globalVar = 10;
2 Declare global variables
3 Define functions // Function declaration
void myFunction();
4 Implement the main
function
int main() {
// Implementation of main function
printf("Hello, C Programming!");
return 0;
}

// Function definition
void myFunction() {
// Implementation of myFunction
}
Embedded C Programming Module-1: Introduction to C 6/62
Basic C Program Structure

Embedded C Programming Module-1: Introduction to C 7/62


Embedded C Program Structure

Interaction with hardware #include <avr/io.h>


Memory considerations
// Declare global variables
Real-time constraints volatile uint8_t sensorValue;

// Function declaration
void initializeSensor();

int main() {
// Implementation of main function
initializeSensor();
while(1) {
// Real-time processing
sensorValue = readSensor();
}
}
void initializeSensor() {
// Hardware initialization
}
uint8_t readSensor() {
// Read data from sensor
}
Embedded C Programming Module-1: Introduction to C 8/62
Find the Output

#include <stdio.h>
int main() {
int x = 5, y = 3;
printf("%d", x + y);
return 0;
}

Embedded C Programming Module-1: Introduction to C 9/62


Find the Output

#include <stdio.h>
int main() {
int x = 5, y = 3;
printf("%d", x + y);
return 0;
}

Answer
The output of the code is 8.

Embedded C Programming Module-1: Introduction to C 9/62


Introduction to Compilation Process

#include <stdio.h>
#define MAX 10

Pre-processing int main() {


Compilation
Assembly int i = MAX;
Linking printf("Maximum value is: %d", i);

return 0;
}
The compilation process converts source code to executable machine code.

Embedded C Programming Module-1: Introduction to C 10/62


Compilation Process

Preprocessor handles directives (like ‘include‘),


compiler translates C to Assembly, assembler to
machine code, linker resolves references.
Tools: C Compiler (e.g., gcc), Assembler (e.g.,
as), Linker (e.g., ld).

Terminal or GCC Compilation


gcc -E main.c -o main.i # Preprocessing
gcc -S main.i -o main.s # Compilation to assembly
as main.s -o main.o # Assembly to object code
ld main.o -o main # Linking object code to
executable

Embedded C Programming Module-1: Introduction to C 11/62


Compilation Process

Embedded C Programming Module-1: Introduction to C 12/62


Comments

Single Line Comment


Used to provide descriptions and explanations in code.
Format: // Comments

Example
#include <stdio.h>
int main(){
// Print statement
printf("Hello World!");
return 0;
}

Comments help document the code functionality and are ignored by


compiler.

Embedded C Programming Module-1: Introduction to C 13/62


Multi-line Comments

Syntax
Used to comment multiple lines or blocks of code.
Format:
/* This is a
multi-line
comment */

Example
/* Comments message
across multiple
lines */
printf("Hello World!");
printf("From C program");

Multi-line comments are convenient for commenting code sections.


Embedded C Programming Module-1: Introduction to C 14/62
Identifiers

Naming Rules
Start with letter or underscore
Can have letters, digits, underscores
Case sensitive index ̸= INDEX
No whitespaces allowed

Example
#include <stdio.h>
int main() {
int final_count; // valid
int 123Invalid; // invalid
return 0;
}

Identifiers refer to user defined names for variables, functions etc. in C.


Embedded C Programming Module-1: Introduction to C 15/62
Variables

Declaring Variables
Specify data type and name: datatype name;

int count;
float price;
char code;

Initializing Variables
Assign initial value: datatype name = value;

int sum = 0;
float pie = 3.14;
char grade = ’A’;
Variables represent memory locations to store program data.

Embedded C Programming Module-1: Introduction to C 16/62


In-depth Variable Types and Storage Classes
Global Variables: Accessible throughout the program. Example: int globalVar;
Local Variables: Accessible only within the function. Example: void func() { int
localVar; }
Static Variables: Retains value between function calls. Example: static int
staticVar;
Register Variables: Stored in CPU register for faster access. Example: register int
loopCounter;
// Global Variable
int globalVar;

void function() {
// Local Variable
int localVar;

// Static Variable
static int staticVar = 0;
staticVar++;

// Register Variable
for(register int i = 0; i < 10; i++) {
// Fast access within loop
}
}

Embedded C Programming Module-1: Introduction to C 17/62


Header Files

# include
Includes external library contents in program:
# include < stdio .h >
# include " myutils . h "

Commonly used library headers in C:


stdio.h - standard I/O functions
math.h - mathematical operations
string.h - string handling
Header files contain reusable code functionalities.

Embedded C Programming Module-1: Introduction to C 18/62


Data Types

Embedded C Programming Module-1: Introduction to C 19/62


Data Types

#include <stdio.h>
int main() {
// Primitive types
int num = 10;
float pi = 3.14;
double height = 79.234;
char x = ’A’;
Primitive types
// Derived types
int, float, double int arr[5];
char struct student {
Derived types int id;
char name[20];
Array, pointer } s1;
Structure, union int* ptr = #

union data {
int i;
float f;
} val;
return 0;
}

Embedded C Programming Module-1: Introduction to C 20/62


Data Types

Character Types % Format Size Range


unsigned char %c 1 byte 0 to 255
char %c 1 byte -128 to 127
signed char %c 1 byte -128 to 127
Integer Types
unsigned short int %hu 2 bytes 0 to 65,535
short int %hd 2 bytes -32,768 to 32,767
signed short int %hd 2 bytes -32,768 to 32,767
unsigned int %u 2/4 bytes 0 to 65,535 or 0 to 4,294,967,295
int %d 2/4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
signed int %d 2/4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
long int %ld 4/8 bytes -2,147,483,648 to 2,147,483,647
unsigned long int %lu 4/8 bytes 0 to 4,294,967,295 or 0 to 18,446,744,073,709,551,615
signed long int %ld 4/8 bytes -2,147,483,648 to 2,147,483,647
long long int %lld 8 bytes -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
unsigned long long int %llu 8 bytes 0 to 18,446,744,073,709,551,615
Float Types
float %f 4 bytes ± 1.2E-38 to ± 3.4E+38
double %lf 8 bytes ± 2.3E-308 to ± 1.7E+308
long double %Lf 12 bytes ± 3.4E–4932 to ± 1.1E+4932

Embedded C Programming Module-1: Introduction to C 21/62


Exploring Data Types and Sizes

#include <stdio.h>
int main() {
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of char: %lu byte\n", sizeof(char));
return 0;
}

Embedded C Programming Module-1: Introduction to C 22/62


Exploring Data Types and Sizes

#include <stdio.h>
int main() {
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of char: %lu byte\n", sizeof(char));
return 0;
}

Question
What will be the output of this program?

Embedded C Programming Module-1: Introduction to C 22/62


Exploring Data Types and Sizes

#include <stdio.h>
int main() {
printf("Size of int: %lu bytes\n", sizeof(int));
printf("Size of char: %lu byte\n", sizeof(char));
return 0;
}

Question
What will be the output of this program?

Answer
The output will display the size of ’int’ and ’char’ in bytes. Typically, it
will be ”Size of int: 4 bytes” and ”Size of char: 1 byte”, but this can vary
depending on the system architecture.

Embedded C Programming Module-1: Introduction to C 22/62


Arithmetic Operators
+ − ∗/%

Arithmetic Operators
x = y + 2 ; // A d d i t i o n
z = p − 5 ; // S u b t r a c t i o n
a r e a = l e n g t h ∗ b r e a d t h ; // M u l t i p l i c a t i o n
q = a / b ; // D i v i s i o n
r = 15 % 4 ; // Modulus

Precedence
Follows order - Exponential > Multiplicative > Additive

a = b + ( c ∗ 2 ) ; // p r e c e d e n c e
z = 3 ∗ x / 5;

i n t num = 1 5 ;
f l o a t v a l = num ; // t y p e c a s t i n g
num + v a l ;

Typecasting allows same operands to be treated as different types.


Embedded C Programming Module-1: Introduction to C 23/62
Relational Operators
> < >= <= ! =
Chaining Relational Operators
i f ( a > 50) // G r e a t e r t h a n
p r i n t f ( ”a i s big ” ) ;

i f ( b < 20) // L e s s t h a n
p r i n t f ( ”b i s s m a l l ” ) ;

i f ( s t r == ” t e s t ” ) // E q u a l t o
p r i n t f ( ” S t r i n g s matched ” ) ;

i f ( i != 1 0 ) // Not e q u a l t o
p r i n t ( ” i i s n o t 10 ” ) ;

i f ( a ge >= 1 8 ) // G r e a t e r t h a n e q u a l t o
printf (” Eligible ” );

i f ( marks <= 3 5 ) // L e s s t h a n e q u a l t o
printf (” Failed ” );

// M u l t i p l e c o n d i t i o n a l c h e c k s can be c h a i n e d :
i f ( x > 5 && x < 1 0 ) {
...
}

Relational operators can be combined using logical operators.


Embedded C Programming Module-1: Introduction to C 24/62
Logical Operators

int a = 5;
int b = 10;

Used to combine multiple logical if(a < 8 && b >= 10) {


conditions: printf("AND condition met");
}
&& - Logical AND
|| - Logical OR if(a < 8 || b < 5) {
! - Logical NOT printf("OR condition met");
}

if(!(b == 15)) {
printf("NOT condition met");
}
Logical operators are used to implement conditional logic.

Embedded C Programming Module-1: Introduction to C 25/62


Bitwise Operators

Used to manipulate individual bits:


& - Bitwise AND : Compares bits
| - Bitwise OR : Makes bits 1 if set in either
b- Bitwise XOR : Makes bits 1 if different
∼ - Bitwise NOT : Inverts all bits
int a = 12; // 0000 1100
int b = 25; // 0001 1001

int c = a & b; // 0000 1000


int d = a | b; // 0001 1101

int e = a ^ 5; // 0000 1101


int f = ~a; // 1111 0011
Bitwise operators perform operations directly on binary representations.

Embedded C Programming Module-1: Introduction to C 26/62


Other Operators
Some other operators in C:
sizeof() - size of type/variable
& - Address of variable
? : - Ternary conditional
, - Comma separates expressions
int a;
float b;

printf("Size of int is %d", sizeof(a));


printf("Address of b is %x", &b);

int x = 5;
int res = (x > 2) ? 10 : 0; // Ternary operator

int y = 1, z = 15; // Comma separates


C provides special operators for certain usage contexts.
Embedded C Programming Module-1: Introduction to C 27/62
Complex Challenge: Data Types and Operators

#include <stdio.h>
int main() {
unsigned int x = 5;
int y = -8;
printf("Result: %s\n", x > y ? "True" : "False");
return 0;
}

Embedded C Programming Module-1: Introduction to C 28/62


Complex Challenge: Data Types and Operators

#include <stdio.h>
int main() {
unsigned int x = 5;
int y = -8;
printf("Result: %s\n", x > y ? "True" : "False");
return 0;
}

Question
What will be the output of this code and why?

Embedded C Programming Module-1: Introduction to C 28/62


Complex Challenge: Data Types and Operators

#include <stdio.h>
int main() {
unsigned int x = 5;
int y = -8;
printf("Result: %s\n", x > y ? "True" : "False");
return 0;
}

Question
What will be the output of this code and why?

Answer
The output is ”False”. This is because when comparing an unsigned int
with an int, the int is implicitly converted to unsigned int. So, -8 is
converted to a large unsigned int value 8, which is greater than 5.

Embedded C Programming Module-1: Introduction to C 28/62


Type Promotion and Arithmetic Operations

#include <stdio.h>
int main() {
short a = 32767; // Max value for short
short b = a + 1;
printf("Result: %d\n", b);
return 0;
}

Embedded C Programming Module-1: Introduction to C 29/62


Type Promotion and Arithmetic Operations

#include <stdio.h>
int main() {
short a = 32767; // Max value for short
short b = a + 1;
printf("Result: %d\n", b);
return 0;
}

Question
What will be the output, and why is this output observed?

Embedded C Programming Module-1: Introduction to C 29/62


Type Promotion and Arithmetic Operations

#include <stdio.h>
int main() {
short a = 32767; // Max value for short
short b = a + 1;
printf("Result: %d\n", b);
return 0;
}

Question
What will be the output, and why is this output observed?

Answer
The output is -32768. In the expression ’a + 1’, ’a’ is first promoted to an
int and then added to 1. The result overflows the range of short, and when
it is stored back in ’b’, it wraps around to the minimum value for a short.

Embedded C Programming Module-1: Introduction to C 29/62


Order of Operations and Associativity

Operator Order (Highest to Lowest) Associativity


() [] -> . 1st Level Left to Right
! ++ -- + (type) - (type) * 2nd Level Right to Left
* / % 3rd Level Left to Right
+ - 4th Level Left to Right
<< >> 5th Level Left to Right
< <= > >= 6th Level Left to Right
== != 7th Level Left to Right
& 8th Level Left to Right
^ 9th Level Left to Right
| 10th Level Left to Right
&& 11th Level Left to Right
|| 12th Level Left to Right
?: 13th Level Right to Left
= += -= *= /= %= &= ^= |= <<= >>= 14th Level Right to Left
, 15th Level Left to Right

Embedded C Programming Module-1: Introduction to C 30/62


Order of Operations - Example Codes
Example 1:
int x = 5;
int y = x + 3 * 2; // y = 11, not 16
Example 2:
int a = 5;
int b = a++ + 2; // b = 7, a becomes 6
Example 3:
int m = 3;
int n = 2 * ++m; // n = 8, m becomes 4
Example 4:
bool p = true;
bool q = !p; // q = false
Example 5:
int i = 4; int j = 5;
int k = i * (j - 2) + 6 / 2 - 3; // k = 4 * (5 - 2) + 3 - 3 = 12
Embedded C Programming Module-1: Introduction to C 31/62
Debugging Challenge: Order of operation

#include <stdio.h>
int main() {
int a = 10, b = 5, c = 5;
int result = a / b * c;
printf("Result: %d\n", result);
return 0;
}

Embedded C Programming Module-1: Introduction to C 32/62


Debugging Challenge: Order of operation

#include <stdio.h>
int main() {
int a = 10, b = 5, c = 5;
int result = a / b * c;
printf("Result: %d\n", result);
return 0;
}

Answer
The output of the code is ”Result: 10”.
The expression is evaluated as (a / b) * c = (10 / 5) * 5 = 2 * 5 = 10.

Embedded C Programming Module-1: Introduction to C 32/62


Debugging Question: Operators

#include <stdio.h>
int main() {
int i = 5;
printf("%d %d %d\n", i++, i, ++i);
return 0;
}

Embedded C Programming Module-1: Introduction to C 33/62


Debugging Question: Operators

#include <stdio.h>
int main() {
int i = 5;
printf("%d %d %d\n", i++, i, ++i);
return 0;
}

Answer
The output of this code is undefined due to the sequence point rule in C.
The order of evaluation of expressions involving post-increment and
pre-increment operators in the same statement is not defined, which leads
to undefined behavior.

Embedded C Programming Module-1: Introduction to C 33/62


Find the Output: Operators Challenge

#include <stdio.h>
int main() {
int x = 2, y = 3, z = 4;
int result = x + y * z / x - y;
printf("Result: %d\n", result);
return 0;
}

Embedded C Programming Module-1: Introduction to C 34/62


Find the Output: Operators Challenge

#include <stdio.h>
int main() {
int x = 2, y = 3, z = 4;
int result = x + y * z / x - y;
printf("Result: %d\n", result);
return 0;
}

Answer
The output of the code is 3. The expression is evaluated as follows: -
Multiplication and division have higher precedence than addition and
subtraction and are evaluated from left to right. - So, y * z / x is
evaluated first to get 6, then x + 6 - y results in 3.

Embedded C Programming Module-1: Introduction to C 34/62


Format Specifiers

Syntax
Used with printf() and scanf() for formatted I/O:
printf("Format string", var1, var2);
scanf("Format string", &var1, &var2);

Some commonly used specifiers:


%c - character
%d - integer
%f - float
%s - string
Format specifiers allow displaying outputs in the desired format.

Embedded C Programming Module-1: Introduction to C 35/62


Format Specifiers

#include <stdio.h>

int main() {
int num = 10;
Some additional specifiers: long int lnum = 15000000;
float flt = 1.234567;
%ld - long integer
double dbl = 1.23456789;
%lf - double float
%Lf - long double printf("Integer: %d\n", num);
printf("Long Integer: %ld\n", lnum);
%x - hex integer printf("Float: %f\n", flt);
%o - octal integer printf("Double: %lf\n", dbl);
printf("Hexadecimal: %x\n", num);
printf("Octal: %o\n", num);

return 0;
}
Format specifiers provide flexibility to print different data types.
Embedded C Programming Module-1: Introduction to C 36/62
Format Specifiers
Format specifiers provide fine grained control over textual output.
Customizing and formatting output:
width and precision
padding and signs
#include <stdio.h>
int main() {
printf("Padding: %-6d\n", 12);
printf("Precision: %.4f\n", 123.4567);
printf("Width: %6d\n", 1234);
printf("Sign: %+d | %+d\n", 10, -10);
return 0;
}

Embedded C Programming Module-1: Introduction to C 37/62


Understanding Format Specifiers Challenge

#include <stdio.h>
int main() {
float num = 12345.6789;
printf("Output: %.2f and %e\n", num, num);
return 0;
}

Embedded C Programming Module-1: Introduction to C 38/62


Understanding Format Specifiers Challenge

#include <stdio.h>
int main() {
float num = 12345.6789;
printf("Output: %.2f and %e\n", num, num);
return 0;
}

Question
What will be the output of this code, considering the format specifiers
used?

Embedded C Programming Module-1: Introduction to C 38/62


Understanding Format Specifiers Challenge

#include <stdio.h>
int main() {
float num = 12345.6789;
printf("Output: %.2f and %e\n", num, num);
return 0;
}

Question
What will be the output of this code, considering the format specifiers
used?

Answer
The output will be ”Output: 12345.68 and 1.234568e+04”. The first
specifier ’formats the float in scientific notation.

Embedded C Programming Module-1: Introduction to C 38/62


Escape Sequences
Escape sequences allow inserting special characters.Used with printf() and
character arrays:
Common Escape Codes
\n - new line - Used for new line
\t - tab - Used for tab spacing
\” - single quote - Prints double quotes
\’ - double quote - Prints single quote

#include <stdio.h>
int main() {
printf("Hello \n World \n");
printf("Name:\tJohn\n");
printf("\"Quotation\" marks\n");
char line[] = "Backslash\escaped";
printf("%s\n", line); Figure: Output
return 0;
} Embedded C Programming Module-1: Introduction to C 39/62
Console I/O
scanf() and printf() are used for formatted console I/O.

Input Output
scanf(”format”, var address); printf(”format”, var);
#include <stdio.h>
int main() {
int age;
float salary;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter salary: ");
scanf("%f", &salary);
printf("Age: %d \n", age);
printf("Salary: %0.2f \n", salary);
return 0;
}
Embedded C Programming Module-1: Introduction to C 40/62
Enhanced I/O Operations

#include <stdio.h>
Formatted I/O: int main() {
printf("Value: %d", a); int number;
char str[100];
and scanf("%d", &a);
// Formatted Input
Unformatted I/O: printf("Enter a number: ");
getchar(); and putchar(); scanf("%d", &number);
printf("You entered: %d\n", number);
Common Pitfalls:
Buffer overflow, improper // Formatted Output
printf("Enter a string: ");
format specifiers. scanf("%s", str);
printf("You entered: %s\n", str);

// Unformatted I/O
char ch;
ch = getchar(); // Reads a character
putchar(ch); // Writes a character
Figure: Output return 0;
}

Embedded C Programming Module-1: Introduction to C 41/62


Unformatted I/O Operations in C

#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads a character from the standard input
printf("Character entered: ");
putchar(ch); // Writes a character to the standard output
return 0;
}
getchar(): Reads a single character from standard input. Waits for
input if not available.
getch(): Similar to getchar() but does not echo the character to the
console. Often used in DOS-based systems.
putchar(): Writes a single character to standard output.
putch(): Similar to putchar() but used in DOS-based systems.

Embedded C Programming Module-1: Introduction to C 42/62


Best Practices and Coding Standards in C

Readability: Use clear and meaningful variable names, consistent


indentation.
Modularity: Break down large problems into smaller, manageable
functions.
Comments: Document the code with necessary comments for better
understanding.
Error Handling: Implement comprehensive error handling for
robustness.
Memory Management: Avoid memory leaks by proper allocation
and deallocation.
Code Reusability: Write reusable code to enhance maintainability.

Embedded C Programming Module-1: Introduction to C 43/62


Best Practices and Coding Standards in C
#include <stdio.h>

int main() {
// Good practice: clear variable names
int totalItems = 10;
int processedItems = 0;

// Good practice: modular code


while (processedItems < totalItems) {
// process each item
processedItems++;
}

// Good practice: error checks and memory management


// Implement necessary checks and memory management

return 0;
}

Embedded C Programming Module-1: Introduction to C 44/62


Best Practices Question

Question
Why is it considered a best practice to initialize all variables in C before
using them? Provide an example.

Embedded C Programming Module-1: Introduction to C 45/62


Best Practices Question

Question
Why is it considered a best practice to initialize all variables in C before
using them? Provide an example.

Answer
Initializing variables prevents undefined behavior due to usage of
uninitialized memory.
For example, without initialization, int x; printf(”% d”, x); might print any
random value. Initializing with int x = 0; ensures ’x’ has a defined,
predictable value.

Embedded C Programming Module-1: Introduction to C 45/62


Common Errors and Troubleshooting in C
Syntax errors: Issues with the code’s structure, often caught by the compiler.
Runtime errors: Errors that occur during the execution of the program, such as division by
zero.
Logic errors: Flaws in the program’s logic leading to incorrect output despite successful
compilation.
Debugging tips: Use of debugger tools, reading compiler warnings, and code reviews.
#include <stdio.h>
int main() {
int a = 10, b = 0;
int result;

// Runtime error example: division by zero


if (b != 0) {
result = a / b;
} else {
printf("Error: Division by zero\n");
}

// Logic error example: incorrect condition


if (a = 10) { // Should be ’==’, not ’=’
printf("a is 10\n");
}

return 0;
} Embedded C Programming Module-1: Introduction to C 46/62
C Programs: Re-usability

Small reusable programs demonstrate language features:

#include <stdio.h>
Math and prime
checks int factorial(int num) {
int f = 1;
String operations for(int i=1; i<=num; i++) {
Sorting f *= i;
}
algorithms return f;
}
File handling
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
int result = factorial(num);
printf("The factorial of %d is %d", num, result);
return 0;
}
Modular programs effectively showcase constructs and libraries.

Embedded C Programming Module-1: Introduction to C 47/62


C Programs : Modularization

Header files modularize functionality:

int add ( int , int ); # include " math . h "


int factorial ( int ); int main () {
int s = add (5 , 10);
int f = factorial (5);
}
Header files and libraries enable code reuse across source files.

Embedded C Programming Module-1: Introduction to C 48/62


Function Call Challenge
#include <stdio.h>
void update(int x) {
x = x + 10;
}
int main() {
int a = 5;
update(a);
printf("a: %d\n", a);
return 0;
}

Embedded C Programming Module-1: Introduction to C 49/62


Function Call Challenge
#include <stdio.h>
void update(int x) {
x = x + 10;
}
int main() {
int a = 5;
update(a);
printf("a: %d\n", a);
return 0;
}

Question
What is the value of ’a’ after the function call and why?

Embedded C Programming Module-1: Introduction to C 49/62


Function Call Challenge
#include <stdio.h>
void update(int x) {
x = x + 10;
}
int main() {
int a = 5;
update(a);
printf("a: %d\n", a);
return 0;
}

Question
What is the value of ’a’ after the function call and why?

Answer
The value of ’a’ remains 5 after the function call. In C, function parameters are
passed by value. Therefore, the function ’update’ modifies a copy of ’a’, not ’a’
itself.
Embedded C Programming Module-1: Introduction to C 49/62
Function Call Challenge: Update with Pointer
#include <stdio.h>
void update(int *x) {
*x = *x + 10;
}
int main() {
int a = 5;
update(&a);
printf("a: %d\n", a);
return 0;
}

Embedded C Programming Module-1: Introduction to C 50/62


Function Call Challenge: Update with Pointer
#include <stdio.h>
void update(int *x) {
*x = *x + 10;
}
int main() {
int a = 5;
update(&a);
printf("a: %d\n", a);
return 0;
}
Question
What is the value of ’a’ after the function call now?

Embedded C Programming Module-1: Introduction to C 50/62


Function Call Challenge: Update with Pointer
#include <stdio.h>
void update(int *x) {
*x = *x + 10;
}
int main() {
int a = 5;
update(&a);
printf("a: %d\n", a);
return 0;
}
Question
What is the value of ’a’ after the function call now?

Answer
Now the value of ’a’ is 15 after the function call. The function ’update’
uses a pointer to directly modify the value of ’a’.
Embedded C Programming Module-1: Introduction to C 50/62
File I/O

File handling allows data persistence across executions.

Opening and closing files #include <stdio.h>


Reading and writing data int main() {
FILE *fptr;
Text vs Binary modes
fptr = fopen("file.txt","w");
fprintf(fptr,"Hello World!");
fclose(fptr);
fptr = fopen("file.txt","r");
char buffer[100];
fscanf(fptr,"%s", buffer);
printf("Data: %s", buffer);
return 0;
}

Embedded C Programming Module-1: Introduction to C 51/62


Basic File Operations in C
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fprintf(fp, "Hello, world!\n");
fclose(fp);
return 0;
}
Opening a File: Use ‘fopen()‘ to open a file. Modes include ”r”, ”w”, ”a”.
Reading from a File: Use ‘fscanf()‘ or ‘fgets()‘ for reading.
Writing to a File: Use ‘fprintf()‘ or ‘fputs()‘ for writing.
Closing a File: Always close a file using ‘fclose()‘.
Error Handling: Check the return value of file operations for errors.
Embedded C Programming Module-1: Introduction to C 52/62
Debugging Challenge: File I/O

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
fprintf(fp, "%d %d %d", 5, 10, 15);
fclose(fp);
return 0;
}

Embedded C Programming Module-1: Introduction to C 53/62


Debugging Challenge: File I/O

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
fprintf(fp, "%d %d %d", 5, 10, 15);
fclose(fp);
return 0;
}

Question
What is the content of ”example.txt” after executing this program?

Embedded C Programming Module-1: Introduction to C 53/62


Debugging Challenge: File I/O

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
fprintf(fp, "%d %d %d", 5, 10, 15);
fclose(fp);
return 0;
}

Question
What is the content of ”example.txt” after executing this program?

Answer
The content of ”example.txt” will be ”5 10 15”. The program writes these
three integers to the file separated by spaces using fprintf.

Embedded C Programming Module-1: Introduction to C 53/62


Preprocessors
Preprocessors handle meta programming logic.
Directives evaluated before compilation
#include, #define, #ifdef etc.
Macro expansions
File inclusion
Conditional compilation

#include <stdio.h>
#define PRINT printf
#define SQUARE(x) x*x

int main() {
PRINT("In main function\n");
int num=5;
PRINT("Square of %d is %d", num, SQUARE(num));
eturn 0;
}
Embedded C Programming Module-1: Introduction to C 54/62
Preprocessors : File Inclusion

Preprocessors insert contents of file during compilation.

include < file > - Search built-in #include <stdio.h>


directories int main() {
include ”file” - Search current printf("Standard library");
directory #include "userdefs.h"
printcustom();
include < file.h > - Header files
return 0;
convention
}
This demonstrates:
Inclusion of stdio.h from built-in folders
Inclusion of userdefs.h from current folder
Calling custom function after inclusion

Embedded C Programming Module-1: Introduction to C 55/62


Preprocessors: Macro Arguments

Macros can make code more readable and maintainable.


Define macros accepting parameters:
# define MACRO (arg1, arg2)
(arg1 + arg2)

#include <stdio.h>

#define MIN(x,y) ((x) < (y) ? (x) : (y))

int main() {
int a = 10, b = 5;
int small = MIN(a, b); //Macro invocation
printf("Minimum of %d & %d is: %d", a, b, small);
return 0;
}

Embedded C Programming Module-1: Introduction to C 56/62


Understanding Macros
#include <stdio.h>
#define SQUARE(x) (x*x)
int main() {
int a = 4, b = 2;
int result = SQUARE(a + b);
printf("Result: %d\n", result);
return 0;
}

Embedded C Programming Module-1: Introduction to C 57/62


Understanding Macros
#include <stdio.h>
#define SQUARE(x) (x*x)
int main() {
int a = 4, b = 2;
int result = SQUARE(a + b);
printf("Result: %d\n", result);
return 0;
}
Question
What is the output of this program and why?

Embedded C Programming Module-1: Introduction to C 57/62


Understanding Macros
#include <stdio.h>
#define SQUARE(x) (x*x)
int main() {
int a = 4, b = 2;
int result = SQUARE(a + b);
printf("Result: %d\n", result);
return 0;
}
Question
What is the output of this program and why?

Answer
The output is 14, not 36. The macro expands to (a + b * a + b), which
is equivalent to (4 + 2 * 4 + 2) due to macro substitution leading to
unexpected results without proper parentheses.
Embedded C Programming Module-1: Introduction to C 57/62
Preprocessors: #if − #else − #endif

Conditionally include code sections during compilation.

{#if CONDITION #define DEBUG


//code A
else int main() {
//code B
#endif } #if DEBUG
This shows: printf("In debug mode\n");
DEBUG macro definition as flag #else
Code inside if block prints when printf("Debug disabled\n");
defined
#endif
Alternate code in else prints
// Rest of code
when not defined
}
#endif

Embedded C Programming Module-1: Introduction to C 58/62


Predefined Macros
Commonly available predefined macros are:
FILE - Current filename
LINE - Current line number
DATE - Compilation date
TIME - Compilation time
#include <stdio.h>
int main() {
printf("Compiled at line %d of file %s \n", LINE, FILE );
printf("On date: %s time: %s\n", DATE, TIME);
return 0;
}
FILE and LINE for displaying context
DATE and TIME for compilation timestamps
Other interesting predefined macros are:
STDC - Conformance level indicator
FUNCTION- Prints function name
Embedded C Programming Module-1: Introduction to C 59/62
Sequential Statements
#include <stdio.h>
// Function declaration
void readInput();
Modular program structure int main() {
// Initialize
Functions, headers, libraries
int num;
Sequence of statements execute
// Read input
top to bottom readInput();
Code blocks, conditionals
// Process
Input, process, output, style num = num * 2;
Program structure best practices // Display output
Statements execute sequentially printf("%d", num);

Overall program flow and stages return 0;


}
Systematic sequence of steps
solve problem. // Define function
void readInput() {
scanf("%d", &num);
}
Embedded C Programming Module-1: Introduction to C 60/62
Modular Programs
Functions follow calling conventions for parameter passing.
// In header.h
int add(int, int);
Functions encapsulate logic:
Declaration in header file // In main.c
Definition with logic #include "header.h"
Call from multiple places
int main() {
This demonstrates: int sum = add(5, 10);
Function declaration in header printf("Sum=%d",sum);
Calling declared function from }
main()
Definition separate from usage // In add.c
int add(int a, int b) {
return a+b;
}
Embedded C Programming Module-1: Introduction to C 61/62
Version Control Basics

Version control systems track changes to files over time.


Git is a distributed version control system widely used in software
development.
Key operations: ‘git init‘, ‘git add‘, ‘git commit‘, ‘git push‘.
Benefits: Collaboration, backup, history, and branch management.
// Command l i n e s n i p p e t s t h a t show b a s i c G i t commands
// Example : I n i t i a l i z i n g a new G i t r e p o s i t o r y
git init

// Adding a f i l e t o t h e s t a g i n g a r e a
g i t add f i l e n a m e . c

// C o m m i t t i n g c h a n g e s w i t h a m e s s a g e
g i t commit −m ” I n i t i a l commit ”

// P u s h i n g c h a n g e s t o a r e m o t e r e p o s i t o r y
g i t pu sh o r i g i n main

Embedded C Programming Module-1: Introduction to C 62/62

You might also like