SlideShare a Scribd company logo
1 of 22
Download to read offline
ECEN 449 – Microprocessor System Design




                 Review of C Programming


Texas A&M University                       1
Objectives of this Lecture Unit

• Review C programming basics
   – Refresh programming skills




Texas A&M University              2
Basic C program structure
# include <stdio.h>
main()
{
  printf (“Hello worldn”);
}

•   Compilation of a program:
     gcc –o hello hello.c --- produces hello as the executable file
     --o specifies the name of the executable file
•   Other flags:
     – Wall – turn on all warnings, useful for debugging purposes
     – o2 – turn optimization on
     – ansi –use ANSI C


Texas A&M University                                                  3
Basic Program Structure

• C programs consist of at least one main() function
   – Can have other functions as needed
• Functions can return values or return nothing
   – void function1 (int arg1, float arg2)
       • Takes an integer as first argument, float as second input
       • Returns no output
   – void function1 (arg1, arg2)
       • int arg1, float arg2;
       • Alternate description of the same function
   – int function2 ()
       • Takes no input, but returns an integer


Texas A&M University                                                 4
Libraries

• C employs many libraries
   – Make it easy to use already written functions in standard libraries
   – stdio.h –standard io –used to input/output data to/from the program
   – Other libraries such as math.h etc exist…




Texas A&M University                                                   5
Data types
•   Int
     – Default size integer
     – Can vary in number of bits, but now mostly 32-bits
•   Short
     – Used normally for 16-bit integers
•   Long
     – Normally 32 bit integers, increasingly 64 bits
•   Unsigned
     – The 32 bits are used for positive numbers, 0…232 -1
•   Float
     – IEEE standard 32-bit floating point number
•   Double
     – Double precision IEEE floating point number, 64 bits
•   Char
     – Used normally for 8-bit characters

Texas A&M University                                          6
Operators

• Assignment A = B;
   – Makes A equal to B
• A-B, A+B, A*B have usual meanings
• A/B depends on the data types
   – Actual division if A is float or double
   – Integer division if A and B are integers (ignore the remainder)
• A%B = remainder of the division
• (A == B)
   – Compares A and B and returns true if A is equal to B else false
• A++ --increment A i.e., A = A+1;
• A-- decrement A i.e., A = A – 1;

Texas A&M University                                                   7
Local vs. Global variables --Scope

• Declared variables have “scope”
• Scope defines where the declared variables are visible
• Global variables
   –   Defined outside any function
   –   Generally placed at the top of the file after include statements
   –   Visible everywhere
   –   Any function can read & modify them
• Local variables
   – Visible only within the functions where declared
   – Allows more control



Texas A&M University                                                      8
Global vs. Local variables

• Safer to use local variables
   – Easier to figure out who is modifying them and debug when problems
     arise
   – Pass information to other functions through values when calling other
     functions
function1 ()
{
  int arg1, arg2;         /* local to function1 */
  float arg3;            /* local to function1 */
  arg3 = function2 (arg1, arg2);
}

Texas A&M University                                                  9
Global vs. local variables
int glob_var1, glob_var2; /* global variables, declared out of scope for all functions
    */

main ()
{
  glob_var1 = 10;
  glob_var2 = 20;
….
}
function1()
{
  glob_var1 = 30;
}

Texas A&M University                                                             10
define

• # define REDDY-PHONE-NUM 8457598
   – Just like a variable, but can’t be changed
   – Visible to everyone
• # define SUM(A, B) A+B
   –   Where ever SUM is used it is replaced with +
   –   For example SUM(3,4) = 3+4
   –   Can be easier to read
   –   Macro function
   –   This is different from a function call
• #define string1 “Aggies Rule”


Texas A&M University                                  11
Loops

• for (i=0; i< 100; i++)
   a[i] = i;

   Another way of doing the same thing:
   i =0;
   while (i <100)
   {
     a[i] = i;
     i++;
   }



Texas A&M University                      12
Arrays & Pointers

• int A[100];
• Declares A as an array of 100 integers from A[0], A[1]…A[99].
• If A[0] is at location 4000 in memory, A[1] is at 4004, A[2] is at
  4008 and so on
   – When int is 4 bytes long
   – Data is stored consecutively in memory
• This gives an alternate way of accessing arrays through pointers
• Pointer is the address where a variable is located
• &A[0] indicates the address of A[0]




Texas A&M University                                                 13
Arrays and pointers

• int *A;
• This declares that A is a pointer and an integer can be accessed
  through this pointer
• There is no space allocated at this pointer i.e., no memory for the
  array.
• A = (int *) malloc(100 * sizeof(int));
• malloc allocates memory space of 100 locations, each the size that
  can hold an int.
• Just to be safe, we cast the pointer to be of integer type by using (int
  *)
• Now *A gives the first value of the array *(A+4) gives the second
  value…so on…

Texas A&M University                                                 14
Pointers

• Pointers are very general
• They can point to integers, floats, chars, arrays, structures,
  functions etc..
• Use the following to be safe:
• int *A, *B; float *C;
  A = malloc (100 * sizeof(int));
  B = (int *) (A + 1); /* B points to A[1] */
        Casting (int *) is safer even though not needed here…
  C = (float *) A[1]; /* what does this say? */



Texas A&M University                                               15
Structures

•  A lot of times we want to group a number of things together.
•  Use struct..
•  Say we want a record of each student for this class
•  Struct student {
       string name[30];
       int uin;
       int score_hw[4];
       int score_exam[2];
       float score_lab[5];
      };
Struct student 449_students[50];

Texas A&M University                                              16
Structures

• 449_students[0] is the structure holding the first students’
  information.
• Individual elements can be accessed by 449_students[0].name,
  449_students[0].uin…etc..
• If you have a pointer to the structure use 449_studentsp->name,
  449_studentsp->uin etc…




Texas A&M University                                                17
I/O

• getchar()
• putchar()
• FILE *fptr;
  fptr = fopen(filename, w);
  for (i= 0; i< 100; i++) fprintf(fptr, “%dn”, i);
  fclose(fptr);
• fscanf(fptr, “%dn”, i);




Texas A&M University                                  18
Function calls and control flow

•   When a function is called –a number of things happen
•   Return address is saved on the stack
•   Local variables saved on the stack
•   Program counter loaded with called function address
•   Function call executed
•   On return, stack is popped to get return address, local variables
•   Execution starts from the returned address




Texas A&M University                                                    19
Open()

• Library:
  include <sys/types.h>;
  include <sys/stat.h>;
  include <fcntl.h>;
• Prototype: int open(char *Path, int Flags);
• Syntax: int fd; char *Path="/tmp/file"; int Flags= O_WRONLY;
  fd = open(Path, Flags);




Texas A&M University                                         20
Mmap()

• Library:
   include <sys/mman.h>
• Syntax:
  void *mmap(void *addr, size_t len, int prot, int flags, int fildes,
  off_t off);
• Usage pa = mmap(addr, len, prot, flags, fildes, off);
Establishes a memory map of file given by fildes (file descriptor),
  starting from offset off, of length len, at memory address starting
  from pa




Texas A&M University                                                21
Mmap()

• prot controls read/write/execute accesses of memory
PROT_READ: read permission
PROT_WRITE: write permission
PROT_EXECUTE: execute permission
PROT_NONE: no permission
Can use OR combination of these bits
• Flags filed controls the type of memory handling
MAP_SHARED: changes are shared
MAP_PRIVATE: changes are not shared



Texas A&M University                                    22

More Related Content

What's hot

Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
 
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked listDrkhanchanaR
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISPNilt1234
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG ManiaplAnkur Shrivastava
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMINGindupps
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File ProcessingRanel Padon
 
07 control+structures
07 control+structures07 control+structures
07 control+structuresbaran19901990
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programmingSudheer Kiran
 
Memory allocation
Memory allocationMemory allocation
Memory allocationsanya6900
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 

What's hot (20)

Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked list
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG Maniapl
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Packages and Datastructures - Python
Packages and Datastructures - PythonPackages and Datastructures - Python
Packages and Datastructures - Python
 
Lisp
LispLisp
Lisp
 
Python ppt
Python pptPython ppt
Python ppt
 
PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMING
 
Python Programming - XII. File Processing
Python Programming - XII. File ProcessingPython Programming - XII. File Processing
Python Programming - XII. File Processing
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Chapter03
Chapter03Chapter03
Chapter03
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
 
Python Basics
Python Basics Python Basics
Python Basics
 
7.0 files and c input
7.0 files and c input7.0 files and c input
7.0 files and c input
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
 
LISP:Program structure in lisp
LISP:Program structure in lispLISP:Program structure in lisp
LISP:Program structure in lisp
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
C
CC
C
 

Viewers also liked

Conventions in Music Magazines
Conventions in Music MagazinesConventions in Music Magazines
Conventions in Music Magazineshhunjan07
 
http://movers.inmaranaaz.com
http://movers.inmaranaaz.comhttp://movers.inmaranaaz.com
http://movers.inmaranaaz.comPhilip Schuck Jr.
 
School Magazine Evaluation
School Magazine EvaluationSchool Magazine Evaluation
School Magazine Evaluationhhunjan07
 
Customize Word Environment
Customize Word EnvironmentCustomize Word Environment
Customize Word EnvironmentCik Na Shohaili
 
A2 exam – g325
A2 exam – g325A2 exam – g325
A2 exam – g325hhunjan07
 
Jawapan peperiksaan percubaan spm 2010 negeri sembilan
Jawapan peperiksaan percubaan spm 2010 negeri sembilanJawapan peperiksaan percubaan spm 2010 negeri sembilan
Jawapan peperiksaan percubaan spm 2010 negeri sembilanCik Na Shohaili
 
Fuerzas laterales
Fuerzas lateralesFuerzas laterales
Fuerzas lateralesanukeme
 
Unit 1.2 : Amanah Pendidikan Moral Ting 5
Unit 1.2 : Amanah Pendidikan Moral Ting 5Unit 1.2 : Amanah Pendidikan Moral Ting 5
Unit 1.2 : Amanah Pendidikan Moral Ting 5Cik Na Shohaili
 

Viewers also liked (8)

Conventions in Music Magazines
Conventions in Music MagazinesConventions in Music Magazines
Conventions in Music Magazines
 
http://movers.inmaranaaz.com
http://movers.inmaranaaz.comhttp://movers.inmaranaaz.com
http://movers.inmaranaaz.com
 
School Magazine Evaluation
School Magazine EvaluationSchool Magazine Evaluation
School Magazine Evaluation
 
Customize Word Environment
Customize Word EnvironmentCustomize Word Environment
Customize Word Environment
 
A2 exam – g325
A2 exam – g325A2 exam – g325
A2 exam – g325
 
Jawapan peperiksaan percubaan spm 2010 negeri sembilan
Jawapan peperiksaan percubaan spm 2010 negeri sembilanJawapan peperiksaan percubaan spm 2010 negeri sembilan
Jawapan peperiksaan percubaan spm 2010 negeri sembilan
 
Fuerzas laterales
Fuerzas lateralesFuerzas laterales
Fuerzas laterales
 
Unit 1.2 : Amanah Pendidikan Moral Ting 5
Unit 1.2 : Amanah Pendidikan Moral Ting 5Unit 1.2 : Amanah Pendidikan Moral Ting 5
Unit 1.2 : Amanah Pendidikan Moral Ting 5
 

Similar to 1 c prog1 (20)

C language
C languageC language
C language
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
C programming
C programmingC programming
C programming
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
dynamic-allocation.pdf
dynamic-allocation.pdfdynamic-allocation.pdf
dynamic-allocation.pdf
 
slides3_077.ppt
slides3_077.pptslides3_077.ppt
slides3_077.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2
 
C programming day#2.
C programming day#2.C programming day#2.
C programming day#2.
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 

Recently uploaded

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

1 c prog1

  • 1. ECEN 449 – Microprocessor System Design Review of C Programming Texas A&M University 1
  • 2. Objectives of this Lecture Unit • Review C programming basics – Refresh programming skills Texas A&M University 2
  • 3. Basic C program structure # include <stdio.h> main() { printf (“Hello worldn”); } • Compilation of a program: gcc –o hello hello.c --- produces hello as the executable file --o specifies the name of the executable file • Other flags: – Wall – turn on all warnings, useful for debugging purposes – o2 – turn optimization on – ansi –use ANSI C Texas A&M University 3
  • 4. Basic Program Structure • C programs consist of at least one main() function – Can have other functions as needed • Functions can return values or return nothing – void function1 (int arg1, float arg2) • Takes an integer as first argument, float as second input • Returns no output – void function1 (arg1, arg2) • int arg1, float arg2; • Alternate description of the same function – int function2 () • Takes no input, but returns an integer Texas A&M University 4
  • 5. Libraries • C employs many libraries – Make it easy to use already written functions in standard libraries – stdio.h –standard io –used to input/output data to/from the program – Other libraries such as math.h etc exist… Texas A&M University 5
  • 6. Data types • Int – Default size integer – Can vary in number of bits, but now mostly 32-bits • Short – Used normally for 16-bit integers • Long – Normally 32 bit integers, increasingly 64 bits • Unsigned – The 32 bits are used for positive numbers, 0…232 -1 • Float – IEEE standard 32-bit floating point number • Double – Double precision IEEE floating point number, 64 bits • Char – Used normally for 8-bit characters Texas A&M University 6
  • 7. Operators • Assignment A = B; – Makes A equal to B • A-B, A+B, A*B have usual meanings • A/B depends on the data types – Actual division if A is float or double – Integer division if A and B are integers (ignore the remainder) • A%B = remainder of the division • (A == B) – Compares A and B and returns true if A is equal to B else false • A++ --increment A i.e., A = A+1; • A-- decrement A i.e., A = A – 1; Texas A&M University 7
  • 8. Local vs. Global variables --Scope • Declared variables have “scope” • Scope defines where the declared variables are visible • Global variables – Defined outside any function – Generally placed at the top of the file after include statements – Visible everywhere – Any function can read & modify them • Local variables – Visible only within the functions where declared – Allows more control Texas A&M University 8
  • 9. Global vs. Local variables • Safer to use local variables – Easier to figure out who is modifying them and debug when problems arise – Pass information to other functions through values when calling other functions function1 () { int arg1, arg2; /* local to function1 */ float arg3; /* local to function1 */ arg3 = function2 (arg1, arg2); } Texas A&M University 9
  • 10. Global vs. local variables int glob_var1, glob_var2; /* global variables, declared out of scope for all functions */ main () { glob_var1 = 10; glob_var2 = 20; …. } function1() { glob_var1 = 30; } Texas A&M University 10
  • 11. define • # define REDDY-PHONE-NUM 8457598 – Just like a variable, but can’t be changed – Visible to everyone • # define SUM(A, B) A+B – Where ever SUM is used it is replaced with + – For example SUM(3,4) = 3+4 – Can be easier to read – Macro function – This is different from a function call • #define string1 “Aggies Rule” Texas A&M University 11
  • 12. Loops • for (i=0; i< 100; i++) a[i] = i; Another way of doing the same thing: i =0; while (i <100) { a[i] = i; i++; } Texas A&M University 12
  • 13. Arrays & Pointers • int A[100]; • Declares A as an array of 100 integers from A[0], A[1]…A[99]. • If A[0] is at location 4000 in memory, A[1] is at 4004, A[2] is at 4008 and so on – When int is 4 bytes long – Data is stored consecutively in memory • This gives an alternate way of accessing arrays through pointers • Pointer is the address where a variable is located • &A[0] indicates the address of A[0] Texas A&M University 13
  • 14. Arrays and pointers • int *A; • This declares that A is a pointer and an integer can be accessed through this pointer • There is no space allocated at this pointer i.e., no memory for the array. • A = (int *) malloc(100 * sizeof(int)); • malloc allocates memory space of 100 locations, each the size that can hold an int. • Just to be safe, we cast the pointer to be of integer type by using (int *) • Now *A gives the first value of the array *(A+4) gives the second value…so on… Texas A&M University 14
  • 15. Pointers • Pointers are very general • They can point to integers, floats, chars, arrays, structures, functions etc.. • Use the following to be safe: • int *A, *B; float *C; A = malloc (100 * sizeof(int)); B = (int *) (A + 1); /* B points to A[1] */ Casting (int *) is safer even though not needed here… C = (float *) A[1]; /* what does this say? */ Texas A&M University 15
  • 16. Structures • A lot of times we want to group a number of things together. • Use struct.. • Say we want a record of each student for this class • Struct student { string name[30]; int uin; int score_hw[4]; int score_exam[2]; float score_lab[5]; }; Struct student 449_students[50]; Texas A&M University 16
  • 17. Structures • 449_students[0] is the structure holding the first students’ information. • Individual elements can be accessed by 449_students[0].name, 449_students[0].uin…etc.. • If you have a pointer to the structure use 449_studentsp->name, 449_studentsp->uin etc… Texas A&M University 17
  • 18. I/O • getchar() • putchar() • FILE *fptr; fptr = fopen(filename, w); for (i= 0; i< 100; i++) fprintf(fptr, “%dn”, i); fclose(fptr); • fscanf(fptr, “%dn”, i); Texas A&M University 18
  • 19. Function calls and control flow • When a function is called –a number of things happen • Return address is saved on the stack • Local variables saved on the stack • Program counter loaded with called function address • Function call executed • On return, stack is popped to get return address, local variables • Execution starts from the returned address Texas A&M University 19
  • 20. Open() • Library: include <sys/types.h>; include <sys/stat.h>; include <fcntl.h>; • Prototype: int open(char *Path, int Flags); • Syntax: int fd; char *Path="/tmp/file"; int Flags= O_WRONLY; fd = open(Path, Flags); Texas A&M University 20
  • 21. Mmap() • Library: include <sys/mman.h> • Syntax: void *mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off); • Usage pa = mmap(addr, len, prot, flags, fildes, off); Establishes a memory map of file given by fildes (file descriptor), starting from offset off, of length len, at memory address starting from pa Texas A&M University 21
  • 22. Mmap() • prot controls read/write/execute accesses of memory PROT_READ: read permission PROT_WRITE: write permission PROT_EXECUTE: execute permission PROT_NONE: no permission Can use OR combination of these bits • Flags filed controls the type of memory handling MAP_SHARED: changes are shared MAP_PRIVATE: changes are not shared Texas A&M University 22