SlideShare a Scribd company logo
The C Language
The C Language Currently, the most commonly-used language for embedded systems “ High-level assembly” Very portable: compilers exist for virtually every processor Easy-to-understand compilation  Produces efficient code Fairly concise
C History Developed between 1969 and 1973 along with Unix Due mostly to Dennis Ritchie Designed for systems programming Operating systems Utility programs Compilers Filters Evolved from B, which evolved from BCPL
BCPL Designed by Martin Richards (Cambridge) in 1967 Typeless Everything an n-bit integer (a machine word) Pointers (addresses) and integers identical Memory is an undifferentiated array of words Natural model for word-addressed machines Local variables depend on frame-pointer-relative addressing: dynamically-sized automatic objects not permitted Strings awkward Routines expand and pack bytes to/from word arrays
C History Original  machine (DEC PDP-11) was very small 24K bytes of memory, 12K used for operating system Written  when  computers were big, capital  equipment Group would get one, develop new language, OS
C History Many   language   features   designed   to   reduce   memory Forward declarations required for everything Designed to work in one pass: must know everything No function nesting PDP-11 was byte-addressed Now standard Meant BCPL’s word-based model was insufficient
Hello World in C #include <stdio.h> void main() { printf(“Hello, world!\n”); } Preprocessor used to share information among source files Clumsy + Cheaply implemented + Very flexible
Hello World in C #include <stdio.h> void main() { printf(“Hello, world!\n”); } Program mostly a collection of functions “ main” function special: the entry point “ void” qualifier indicates function does not return anything I/O performed by a library function: not included in the language
Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } “ New Style” function declaration lists number and type of arguments Originally only listed return type. Generated code did not care how many arguments were actually passed. Arguments are call-by-value
Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } Automatic variable Storage allocated on stack when function entered, released when it returns. All parameters, automatic variables accessed w.r.t. frame pointer. Extra storage needed while evaluating large expressions also placed on the stack n m ret. addr. r Frame pointer Stack pointer Excess arguments simply ignored
Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } Expression: C’s basic type of statement. Arithmetic and logical Assignment (=) returns a value, so can be used in expressions % is remainder != is not equal
Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } High-level control-flow statement. Ultimately becomes a conditional branch. Supports “structured programming” Each function returns a single value, usually an integer. Returned through a specific register by convention.
Pieces of C Types and Variables Definitions of data in memory Expressions Arithmetic, logical, and assignment operators in an infix notation Statements Sequences of conditional, iteration, and branching instructions Functions Groups of statements and variables invoked recursively
C Types Basic types: char, int, float, and double Meant to match the processor’s native types Natural translation into assembly Fundamentally nonportable Declaration syntax: string of specifiers followed by a declarator Declarator’s notation matches that in an expression Access a symbol using its declarator and get the basic type back
C Type Examples int i; int *j, k; unsigned char *ch; float f[10]; char nextChar(int, char*); int a[3][5][10]; int *func1(float); int (*func2)(void); Integer j: pointer to integer, int k ch: pointer to unsigned char Array of 10 floats 2-arg function Array of three arrays of five … function returning int * pointer to function returning int
C Typedef Type declarations recursive, complicated. Name new types with typedef  Instead of int (*func2)(void) use typedef int func2t(void); func2t *func2;
C Structures A struct is an object with named fields: struct { char *name; int x, y; int h, w; } box; Accessed using “dot” notation: box.x = 5; box.y = 2;
Struct bit-fields Way to aggressively pack data in memory struct { unsigned int baud : 5; unsigned int div2 : 1; unsigned int use_external_clock : 1; } flags; Compiler will pack these fields into words Very implementation dependent: no guarantees of ordering, packing, etc. Usually less efficient Reading a field requires masking and shifting
C Unions Can store objects of different types at different times union { int ival; float fval; char *sval; }; Useful for arrays of dissimilar objects Potentially very dangerous Good example of C’s philosophy Provide powerful mechanisms that can be abused
Alignment of data in structs Most processors require n-byte objects to be in memory at address n*k Side effect of wide memory busses E.g., a 32-bit memory bus Read from address 3 requires two accesses, shifting 4 3 2 1 4 3 2 1
Alignment of data in structs Compilers add “padding” to structs to ensure proper alignment, especially for arrays Pad to ensure alignment of largest object (with biggest requirement) struct { char a; int b; char c; } Moral: rearrange to save memory a b b b b c a b b b b c Pad
C Storage Classes #include <stdlib.h> int global_static; static int file_static; void foo(int auto_param) { static int func_static; int auto_i, auto_a[10]; double *auto_d = malloc(sizeof(double)*5); } Linker-visible. Allocated at fixed location Visible within file. Allocated at fixed location. Visible within func. Allocated at fixed location.
C Storage Classes #include <stdlib.h> int global_static; static int file_static; void foo(int auto_param) { static int func_static; int auto_i, auto_a[10]; double *auto_d = malloc(sizeof(double)*5); } Space allocated on stack by function. Space allocated on stack by caller. Space allocated on heap by library routine.
malloc() and free() Library routines for managing the heap int *a; a = (int *) malloc(sizeof(int) * k);  a[5] = 3; free(a); Allocate and free arbitrary-sized chunks of memory in any order
malloc() and free() More flexible than automatic variables (stacked) More costly in time and space malloc() and free() use complicated non-constant-time algorithms Each block generally consumes two additional words of memory Pointer to next empty block Size of this block Common source of errors Using uninitialized memory Using freed memory Not allocating enough Neglecting to free disused blocks (memory leaks)
malloc() and free() Memory usage errors so pervasive, entire successful company (Pure Software) founded to sell tool to track them down Purify tool inserts code that verifies each memory access Reports accesses of uninitialized memory, unallocated memory, etc. Publicly-available Electric Fence tool does something similar
Dynamic Storage Allocation What are malloc() and free() actually doing? Pool of memory segments: Free malloc( )
Dynamic Storage Allocation Rules: Each segment contiguous in memory (no holes) Segments do not move once allocated malloc() Find memory area large enough for segment Mark that memory is allocated free() Mark the segment as unallocated
Dynamic Storage Allocation Three issues: How to maintain information about free memory The algorithm for locating a suitable block The algorithm for freeing an allocated block
Simple Dynamic Storage Allocation Three issues: How to maintain information about free memory Linked list The algorithm for locating a suitable block First-fit The algorithm for freeing an allocated block Coalesce adjacent free blocks
Arrays Array: sequence of identical objects in memory int a[10]; means space for ten integers By itself, a is the address of the first integer *a and a[0] mean the same thing The address of a is not stored in memory: the compiler inserts code to compute it when it appears Ritchie calls this interpretation the biggest conceptual jump from BCPL to C
Multidimensional Arrays Array declarations read right-to-left int a[10][3][2]; “ an array of ten arrays of three arrays of two ints” In memory 2 2 2 3 2 2 2 3 2 2 2 3 ... 10
Multidimensional Arrays Passing a multidimensional array as an argument requires all but the first dimension int a[10][3][2]; void examine( a[][3][2] ) { … } Address for an access such as a[i][j][k] is a + k + 2*(j + 3*i)
Multidimensional Arrays Use arrays of pointers for variable-sized multidimensional arrays You need to allocate space for and initialize the arrays of pointers int ***a; a[3][5][4] expands to *(*(*(a+3)+5)+4) The value int ** int * int int ***a
C Expressions Traditional mathematical expressions y = a*x*x + b*x + c; Very rich set of expressions Able to deal with arithmetic and bit manipulation
C Expression Classes arithmetic: + – * / %  comparison: == != < <= > >= bitwise logical: & | ^ ~ shifting: << >> lazy logical: && || ! conditional: ? : assignment: = += -= increment/decrement: ++ -- sequencing: , pointer: * -> & []
Bitwise operators and: & or: | xor: ^ not: ~ left shift: << right shift: >> Useful for bit-field manipulations #define MASK 0x040 if (a & MASK) { … } /* Check bits */ c |= MASK; /* Set bits */ c &= ~MASK; /* Clear bits */ d = (a & MASK) >> 4; /* Select field */
Lazy Logical Operators “ Short circuit” tests save time if ( a == 3 && b == 4 && c == 5 ) { … } equivalent to if (a == 3) { if (b ==4) { if (c == 5) { … } } } Evaluation order (left before right) provides safety if ( i <= SIZE && a[i] == 0 ) { … }                                                                                                                       
Conditional Operator c = a < b ? a + 1 : b – 1; Evaluate first expression.  If true, evaluate second, otherwise evaluate third. Puts almost statement-like behavior in expressions. BCPL allowed code in an expression: a := 5 + valof{ int i, s = 0; for (i = 0 ; i < 10 ; i++) s += a[I]; return s; }
Side-effects in expressions Evaluating an expression often has side-effects a++ increment a afterwards a = 5 changes the value of a a = foo()  function foo may have side-effects
Pointer Arithmetic From BCPL’s view of the world Pointer arithmetic is natural: everything’s an integer int *p, *q; *(p+5) equivalent to p[5] If p and q point into same array, p – q is number of elements between p and q. Accessing fields of a pointed-to structure has a shorthand: p->field means (*p).field
C Statements Expression Conditional if (expr) { … } else {…} switch (expr) { case c1: case c2: … } Iteration while (expr) { … } zero or more iterations do … while (expr) at least one iteration for ( init ; valid ; next ) { … } Jump goto label continue; go to start of loop break; exit loop or switch return expr; return from function
The Switch Statement Performs multi-way branches switch (expr) { case 1: … break; case 5: case 6: … break; default: … break; } tmp = expr; if (tmp == 1) goto L1 else if (tmp == 5) goto L5 else if (tmp == 6) goto L6 else goto Default; L1: … goto Break; L5:; L6: … goto Break; Default: … goto Break; Break:
Switch Generates Interesting Code Sparse case labels tested sequentially if (e == 1) goto L1; else if (e == 10) goto L2; else if (e == 100) goto L3; Dense cases use a jump table table = { L1, L2, Default, L4, L5 }; if (e >= 1 and e <= 5) goto table[e]; Clever compilers may combine these
Summary C evolved from the typeless languages BCPL and B Array-of-bytes model of memory permeates the language Original weak type system strengthened over time C programs built from Variable and type declarations Functions Statements Expressions
Ad

More Related Content

What's hot (20)

1. importance of c
1. importance of c1. importance of c
1. importance of c
Alamgir Hossain
 
Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C Language
RAJWANT KAUR
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
C basics
C   basicsC   basics
C basics
thirumalaikumar3
 
File handling in c
File handling in cFile handling in c
File handling in c
David Livingston J
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
TejaswiB4
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
Manoj Tyagi
 
C++ programming
C++ programmingC++ programming
C++ programming
Emertxe Information Technologies Pvt Ltd
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
ForwardBlog Enewzletter
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
temkin abdlkader
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
Chitrank Dixit
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
David Livingston J
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Vijay A Raj
 
If else statement in c++
If else statement in c++If else statement in c++
If else statement in c++
Bishal Sharma
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
Kamal Acharya
 
C fundamental
C fundamentalC fundamental
C fundamental
Selvam Edwin
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
C language ppt
C language pptC language ppt
C language ppt
Ğäùråv Júñêjå
 

Viewers also liked (10)

C language
C languageC language
C language
spatidar0
 
Programming C Language
Programming C LanguageProgramming C Language
Programming C Language
natarafonseca
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
Open Gurukul
 
C++ loop
C++ loop C++ loop
C++ loop
Khelan Ameen
 
ERD Case scenario
ERD Case scenarioERD Case scenario
ERD Case scenario
markthesuth
 
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
Loops in C
Loops in CLoops in C
Loops in C
Kamal Acharya
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
Vineet Kumar Saini
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
Durga Padma
 
Array in c language
Array in c languageArray in c language
Array in c language
home
 
Programming C Language
Programming C LanguageProgramming C Language
Programming C Language
natarafonseca
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
Open Gurukul
 
ERD Case scenario
ERD Case scenarioERD Case scenario
ERD Case scenario
markthesuth
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
Vineet Kumar Saini
 
Array in c language
Array in c languageArray in c language
Array in c language
home
 
Ad

Similar to Clanguage (20)

C language
C languageC language
C language
VAIRA MUTHU
 
C language introduction
C language introduction C language introduction
C language introduction
musrath mohammad
 
Theory1&amp;2
Theory1&amp;2Theory1&amp;2
Theory1&amp;2
Dr.M.Karthika parthasarathy
 
Introduction to c language and its application.ppt
Introduction to c language and its application.pptIntroduction to c language and its application.ppt
Introduction to c language and its application.ppt
ParilittleAngel
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
Saifur Rahman
 
C Programming language
C Programming languageC Programming language
C Programming language
Rokonuzzaman Rony
 
Clanguage
ClanguageClanguage
Clanguage
Abhishek Khune
 
Clanguage
ClanguageClanguage
Clanguage
Abhishek Khune
 
anjaan007
anjaan007anjaan007
anjaan007
aswath babu
 
Clanguage
ClanguageClanguage
Clanguage
subhajitmondalglb
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
C_Progragramming_language_Tutorial_ppt_f.pptx
C_Progragramming_language_Tutorial_ppt_f.pptxC_Progragramming_language_Tutorial_ppt_f.pptx
C_Progragramming_language_Tutorial_ppt_f.pptx
maaithilisaravanan
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
Prerna Sharma
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
amol_chavan
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
Dushmanta Nath
 
C
CC
C
Khan Rahimeen
 
C
CC
C
Anuja Lad
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
Atul Setu
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
mspline
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
Syed Zaid Irshad
 
Ad

More from Vidyacenter (6)

Example Projectile Motion
Example Projectile MotionExample Projectile Motion
Example Projectile Motion
Vidyacenter
 
Advance Java
Advance JavaAdvance Java
Advance Java
Vidyacenter
 
C++ Language
C++ LanguageC++ Language
C++ Language
Vidyacenter
 
Interview Tips
Interview TipsInterview Tips
Interview Tips
Vidyacenter
 
Gre Ppt
Gre PptGre Ppt
Gre Ppt
Vidyacenter
 
Gmat Ppt
Gmat PptGmat Ppt
Gmat Ppt
Vidyacenter
 

Recently uploaded (20)

Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 

Clanguage

  • 2. The C Language Currently, the most commonly-used language for embedded systems “ High-level assembly” Very portable: compilers exist for virtually every processor Easy-to-understand compilation Produces efficient code Fairly concise
  • 3. C History Developed between 1969 and 1973 along with Unix Due mostly to Dennis Ritchie Designed for systems programming Operating systems Utility programs Compilers Filters Evolved from B, which evolved from BCPL
  • 4. BCPL Designed by Martin Richards (Cambridge) in 1967 Typeless Everything an n-bit integer (a machine word) Pointers (addresses) and integers identical Memory is an undifferentiated array of words Natural model for word-addressed machines Local variables depend on frame-pointer-relative addressing: dynamically-sized automatic objects not permitted Strings awkward Routines expand and pack bytes to/from word arrays
  • 5. C History Original machine (DEC PDP-11) was very small 24K bytes of memory, 12K used for operating system Written when computers were big, capital equipment Group would get one, develop new language, OS
  • 6. C History Many language features designed to reduce memory Forward declarations required for everything Designed to work in one pass: must know everything No function nesting PDP-11 was byte-addressed Now standard Meant BCPL’s word-based model was insufficient
  • 7. Hello World in C #include <stdio.h> void main() { printf(“Hello, world!\n”); } Preprocessor used to share information among source files Clumsy + Cheaply implemented + Very flexible
  • 8. Hello World in C #include <stdio.h> void main() { printf(“Hello, world!\n”); } Program mostly a collection of functions “ main” function special: the entry point “ void” qualifier indicates function does not return anything I/O performed by a library function: not included in the language
  • 9. Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } “ New Style” function declaration lists number and type of arguments Originally only listed return type. Generated code did not care how many arguments were actually passed. Arguments are call-by-value
  • 10. Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } Automatic variable Storage allocated on stack when function entered, released when it returns. All parameters, automatic variables accessed w.r.t. frame pointer. Extra storage needed while evaluating large expressions also placed on the stack n m ret. addr. r Frame pointer Stack pointer Excess arguments simply ignored
  • 11. Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } Expression: C’s basic type of statement. Arithmetic and logical Assignment (=) returns a value, so can be used in expressions % is remainder != is not equal
  • 12. Euclid’s algorithm in C int gcd(int m, int n) { int r; while ( (r = m % n) != 0) { m = n; n = r; } return n; } High-level control-flow statement. Ultimately becomes a conditional branch. Supports “structured programming” Each function returns a single value, usually an integer. Returned through a specific register by convention.
  • 13. Pieces of C Types and Variables Definitions of data in memory Expressions Arithmetic, logical, and assignment operators in an infix notation Statements Sequences of conditional, iteration, and branching instructions Functions Groups of statements and variables invoked recursively
  • 14. C Types Basic types: char, int, float, and double Meant to match the processor’s native types Natural translation into assembly Fundamentally nonportable Declaration syntax: string of specifiers followed by a declarator Declarator’s notation matches that in an expression Access a symbol using its declarator and get the basic type back
  • 15. C Type Examples int i; int *j, k; unsigned char *ch; float f[10]; char nextChar(int, char*); int a[3][5][10]; int *func1(float); int (*func2)(void); Integer j: pointer to integer, int k ch: pointer to unsigned char Array of 10 floats 2-arg function Array of three arrays of five … function returning int * pointer to function returning int
  • 16. C Typedef Type declarations recursive, complicated. Name new types with typedef Instead of int (*func2)(void) use typedef int func2t(void); func2t *func2;
  • 17. C Structures A struct is an object with named fields: struct { char *name; int x, y; int h, w; } box; Accessed using “dot” notation: box.x = 5; box.y = 2;
  • 18. Struct bit-fields Way to aggressively pack data in memory struct { unsigned int baud : 5; unsigned int div2 : 1; unsigned int use_external_clock : 1; } flags; Compiler will pack these fields into words Very implementation dependent: no guarantees of ordering, packing, etc. Usually less efficient Reading a field requires masking and shifting
  • 19. C Unions Can store objects of different types at different times union { int ival; float fval; char *sval; }; Useful for arrays of dissimilar objects Potentially very dangerous Good example of C’s philosophy Provide powerful mechanisms that can be abused
  • 20. Alignment of data in structs Most processors require n-byte objects to be in memory at address n*k Side effect of wide memory busses E.g., a 32-bit memory bus Read from address 3 requires two accesses, shifting 4 3 2 1 4 3 2 1
  • 21. Alignment of data in structs Compilers add “padding” to structs to ensure proper alignment, especially for arrays Pad to ensure alignment of largest object (with biggest requirement) struct { char a; int b; char c; } Moral: rearrange to save memory a b b b b c a b b b b c Pad
  • 22. C Storage Classes #include <stdlib.h> int global_static; static int file_static; void foo(int auto_param) { static int func_static; int auto_i, auto_a[10]; double *auto_d = malloc(sizeof(double)*5); } Linker-visible. Allocated at fixed location Visible within file. Allocated at fixed location. Visible within func. Allocated at fixed location.
  • 23. C Storage Classes #include <stdlib.h> int global_static; static int file_static; void foo(int auto_param) { static int func_static; int auto_i, auto_a[10]; double *auto_d = malloc(sizeof(double)*5); } Space allocated on stack by function. Space allocated on stack by caller. Space allocated on heap by library routine.
  • 24. malloc() and free() Library routines for managing the heap int *a; a = (int *) malloc(sizeof(int) * k); a[5] = 3; free(a); Allocate and free arbitrary-sized chunks of memory in any order
  • 25. malloc() and free() More flexible than automatic variables (stacked) More costly in time and space malloc() and free() use complicated non-constant-time algorithms Each block generally consumes two additional words of memory Pointer to next empty block Size of this block Common source of errors Using uninitialized memory Using freed memory Not allocating enough Neglecting to free disused blocks (memory leaks)
  • 26. malloc() and free() Memory usage errors so pervasive, entire successful company (Pure Software) founded to sell tool to track them down Purify tool inserts code that verifies each memory access Reports accesses of uninitialized memory, unallocated memory, etc. Publicly-available Electric Fence tool does something similar
  • 27. Dynamic Storage Allocation What are malloc() and free() actually doing? Pool of memory segments: Free malloc( )
  • 28. Dynamic Storage Allocation Rules: Each segment contiguous in memory (no holes) Segments do not move once allocated malloc() Find memory area large enough for segment Mark that memory is allocated free() Mark the segment as unallocated
  • 29. Dynamic Storage Allocation Three issues: How to maintain information about free memory The algorithm for locating a suitable block The algorithm for freeing an allocated block
  • 30. Simple Dynamic Storage Allocation Three issues: How to maintain information about free memory Linked list The algorithm for locating a suitable block First-fit The algorithm for freeing an allocated block Coalesce adjacent free blocks
  • 31. Arrays Array: sequence of identical objects in memory int a[10]; means space for ten integers By itself, a is the address of the first integer *a and a[0] mean the same thing The address of a is not stored in memory: the compiler inserts code to compute it when it appears Ritchie calls this interpretation the biggest conceptual jump from BCPL to C
  • 32. Multidimensional Arrays Array declarations read right-to-left int a[10][3][2]; “ an array of ten arrays of three arrays of two ints” In memory 2 2 2 3 2 2 2 3 2 2 2 3 ... 10
  • 33. Multidimensional Arrays Passing a multidimensional array as an argument requires all but the first dimension int a[10][3][2]; void examine( a[][3][2] ) { … } Address for an access such as a[i][j][k] is a + k + 2*(j + 3*i)
  • 34. Multidimensional Arrays Use arrays of pointers for variable-sized multidimensional arrays You need to allocate space for and initialize the arrays of pointers int ***a; a[3][5][4] expands to *(*(*(a+3)+5)+4) The value int ** int * int int ***a
  • 35. C Expressions Traditional mathematical expressions y = a*x*x + b*x + c; Very rich set of expressions Able to deal with arithmetic and bit manipulation
  • 36. C Expression Classes arithmetic: + – * / % comparison: == != < <= > >= bitwise logical: & | ^ ~ shifting: << >> lazy logical: && || ! conditional: ? : assignment: = += -= increment/decrement: ++ -- sequencing: , pointer: * -> & []
  • 37. Bitwise operators and: & or: | xor: ^ not: ~ left shift: << right shift: >> Useful for bit-field manipulations #define MASK 0x040 if (a & MASK) { … } /* Check bits */ c |= MASK; /* Set bits */ c &= ~MASK; /* Clear bits */ d = (a & MASK) >> 4; /* Select field */
  • 38. Lazy Logical Operators “ Short circuit” tests save time if ( a == 3 && b == 4 && c == 5 ) { … } equivalent to if (a == 3) { if (b ==4) { if (c == 5) { … } } } Evaluation order (left before right) provides safety if ( i <= SIZE && a[i] == 0 ) { … }                                                                                                                       
  • 39. Conditional Operator c = a < b ? a + 1 : b – 1; Evaluate first expression. If true, evaluate second, otherwise evaluate third. Puts almost statement-like behavior in expressions. BCPL allowed code in an expression: a := 5 + valof{ int i, s = 0; for (i = 0 ; i < 10 ; i++) s += a[I]; return s; }
  • 40. Side-effects in expressions Evaluating an expression often has side-effects a++ increment a afterwards a = 5 changes the value of a a = foo() function foo may have side-effects
  • 41. Pointer Arithmetic From BCPL’s view of the world Pointer arithmetic is natural: everything’s an integer int *p, *q; *(p+5) equivalent to p[5] If p and q point into same array, p – q is number of elements between p and q. Accessing fields of a pointed-to structure has a shorthand: p->field means (*p).field
  • 42. C Statements Expression Conditional if (expr) { … } else {…} switch (expr) { case c1: case c2: … } Iteration while (expr) { … } zero or more iterations do … while (expr) at least one iteration for ( init ; valid ; next ) { … } Jump goto label continue; go to start of loop break; exit loop or switch return expr; return from function
  • 43. The Switch Statement Performs multi-way branches switch (expr) { case 1: … break; case 5: case 6: … break; default: … break; } tmp = expr; if (tmp == 1) goto L1 else if (tmp == 5) goto L5 else if (tmp == 6) goto L6 else goto Default; L1: … goto Break; L5:; L6: … goto Break; Default: … goto Break; Break:
  • 44. Switch Generates Interesting Code Sparse case labels tested sequentially if (e == 1) goto L1; else if (e == 10) goto L2; else if (e == 100) goto L3; Dense cases use a jump table table = { L1, L2, Default, L4, L5 }; if (e >= 1 and e <= 5) goto table[e]; Clever compilers may combine these
  • 45. Summary C evolved from the typeless languages BCPL and B Array-of-bytes model of memory permeates the language Original weak type system strengthened over time C programs built from Variable and type declarations Functions Statements Expressions