Embedded - C - Module1 New
Embedded - C - Module1 New
Module-1: Introduction to C
Example Program:
#include <stdio.h>
int main() {
printf("Hello World \n");
return 0;
}
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.
// Function definition
void myFunction() {
// Implementation of myFunction
}
Embedded C Programming Module-1: Introduction to C 6/62
Basic C Program Structure
// 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;
}
#include <stdio.h>
int main() {
int x = 5, y = 3;
printf("%d", x + y);
return 0;
}
Answer
The output of the code is 8.
#include <stdio.h>
#define MAX 10
return 0;
}
The compilation process converts source code to executable machine code.
Example
#include <stdio.h>
int main(){
// Print statement
printf("Hello World!");
return 0;
}
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");
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;
}
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.
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
}
}
# include
Includes external library contents in program:
# include < stdio .h >
# include " myutils . h "
#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;
}
#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;
}
#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?
#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.
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 ;
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 ) {
...
}
int a = 5;
int b = 10;
if(!(b == 15)) {
printf("NOT condition met");
}
Logical operators are used to implement conditional logic.
int x = 5;
int res = (x > 2) ? 10 : 0; // Ternary operator
#include <stdio.h>
int main() {
unsigned int x = 5;
int y = -8;
printf("Result: %s\n", x > y ? "True" : "False");
return 0;
}
#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?
#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.
#include <stdio.h>
int main() {
short a = 32767; // Max value for short
short b = a + 1;
printf("Result: %d\n", b);
return 0;
}
#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?
#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.
#include <stdio.h>
int main() {
int a = 10, b = 5, c = 5;
int result = a / b * c;
printf("Result: %d\n", result);
return 0;
}
#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.
#include <stdio.h>
int main() {
int i = 5;
printf("%d %d %d\n", i++, i, ++i);
return 0;
}
#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.
#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;
}
#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.
Syntax
Used with printf() and scanf() for formatted I/O:
printf("Format string", var1, var2);
scanf("Format string", &var1, &var2);
#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;
}
#include <stdio.h>
int main() {
float num = 12345.6789;
printf("Output: %.2f and %e\n", num, num);
return 0;
}
#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?
#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.
#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;
}
#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.
int main() {
// Good practice: clear variable names
int totalItems = 10;
int processedItems = 0;
return 0;
}
Question
Why is it considered a best practice to initialize all variables in C before
using them? Provide an example.
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.
return 0;
} Embedded C Programming Module-1: Introduction to C 46/62
C Programs: Re-usability
#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.
Question
What is the value of ’a’ after the function call and why?
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;
}
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
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w");
fprintf(fp, "%d %d %d", 5, 10, 15);
fclose(fp);
return 0;
}
#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?
#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.
#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
#include <stdio.h>
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;
}
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
// 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