SlideShare a Scribd company logo
1 of 30
Download to read offline
Operating Systems
         CMPSCI 377
            C/C++
                   Emery Berger
University of Massachusetts Amherst




UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science
Why C?




  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   2
Why C?
    Low-level


        Direct access to memory
    

        WYSIWYG (more or less)
    

        Effectively no runtime system
    

              No garbage collector
          

              No other threads
          

              No “read” or “write barriers”
          


    Efficient


        Space & time
    

        C: effectively portable assembly code
    


        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   3
OK, Why C++?




  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   4
OK, Why C++?
    C++: extends C


        Upwardly-compatible
    

    Adds significant software engineering


    benefits
        Classes
    

        Encapsulation (private)
    

        Templates (“generics”)
    

        Other modularity advantages
    

        Inlining instead of macros
    



        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   5
Outline, part I
    Basics – compiling & running


    Intrinsic types, conditionals, etc.


    Pointers + Reference variables


        Assignment
    

        Objects
    

        &, *, ->
    

    Stack vs. heap





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   6
Outline, part II
    Functions


        Parameter passing
    

    Structs & classes


    Overloading & inheritance


    Stack vs. heap


    I/O, command-line


    STL





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   7
Basics
    Main & compilation





     UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   8
Intrinsic Types
    Essentially identical





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   9
Conditionals
    Mostly the same


        C/C++: nonzero int same as true
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   10
File I/O
    Simple stream-based I/O


                                               print foo
        cout << “foo”
    

                                               read x from the console
        cin >> x
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   11
Command-line Arguments
    Again, similar to Java





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   12
Key Differences
    Differences between C/C++ and Java


        Assignment
    

        Pointers
    

        Parameter passing
    

        Heap & Stack
    

        Arrays
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   13
Assignment
    Java assignment: makes reference


    C++ assignment: makes copy





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   14
Pointers & Friends

    Pointers are like jumps, leading wildly from


    one part of the data structure to another.
    Their introduction into high-level languages
    has been a step backwards from which we
    may never recover.
                                    C.A.R. Hoare




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   15
Pointers & Friends
    Concept not in Java: address manipulation





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   16
Functions & Parameter Passing
    C/C++ – all parameters copied by default





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   17
Parameter Passing
    To change input, pass pointer


    or call by reference




      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   18
Pass by Reference
    Syntactic sugar:


    foo (int &i) = pass by reference
        Secretly does pointer stuff for you
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   19
Stack & Heap




   UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   20
Stack & Heap
    In C/C++ as in Java, objects can live on


    stack or on heap
        Stack = region of memory for temporaries
    

              Stack pointer pushed on function entry
          

              Popped on function exit
          


        Heap = distinct region of memory for
    

        persistent objects
              C/C++ – explicitly managed
          


    Pointers introduce problems!





        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   21
The Stack
    Stack data: new every time





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   22
Big Stack Mistake
    Never return pointers to the stack!





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   23
The Heap
    Allocate persistent data on heap with new





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   24
Explicit Memory Management
    Java heap – garbage collected


    C/C++ – explicit memory management


        You must delete items (or memory leak)
    




        Delete them too soon (still in use) – crash
    

              “Dangling pointer” error
          


        Delete something twice – crash
    

              “Double-free” error
          


        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   25
Classes & Objects
    No “top” object (as in Java Object)


        Also: C++ has no interfaces but has multiple
    

        inheritance – stay far away
    Key difference for you – not all methods

    dynamically-dispatched
        Methods associated with declared type
    

        rather than dynamic type unless labeled
        virtual



        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   26
Struct Member Access
    struct = class with everything public


        Use these sparingly
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   27
Class Declaration
    Pretty similar





      UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   28
Arrays
    Numerous differences


        Arrays do not have to be allocated with new
    

        Array bounds not checked
    

        Item[0] = pointer to start of array
    

        Arrays just syntactic sugar
    

        for pointer arithmetic! (scary! avoid!)
              v = 12; *(Item + v) = 1;
          


              Same as Item[12] = 1;
          


        Note: sizeof(x) = number of bytes to hold x
    

    Multi-dimensional arrays (matrices)


        just arrays of pointers to arrays
    
        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   29
Other Features
    Operator overloading


        New meanings to existing operators
    

              int operator+(MyType& a, MyType& b);
          


        Controversial, but useful for things like
    

        complex math, matrix operations
              int& operator()(int x, int y);
          


    Templates


        A.k.a. generics in Java
    

        template <class X> void foo (X arg);
    




        UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science   30

More Related Content

Viewers also liked

Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
Assembly language 8086 intermediate
Assembly language 8086 intermediateAssembly language 8086 intermediate
Assembly language 8086 intermediate
John Cutajar
 

Viewers also liked (14)

Maharashtra hsc board previous year papers
Maharashtra hsc board  previous year papersMaharashtra hsc board  previous year papers
Maharashtra hsc board previous year papers
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Assembly language 8086 intermediate
Assembly language 8086 intermediateAssembly language 8086 intermediate
Assembly language 8086 intermediate
 
Bubblesort Algorithm
Bubblesort AlgorithmBubblesort Algorithm
Bubblesort Algorithm
 
Bubble sort a best presentation topic
Bubble sort a best presentation topicBubble sort a best presentation topic
Bubble sort a best presentation topic
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Inheritance
InheritanceInheritance
Inheritance
 
Career Option after 10+2
Career Option after 10+2Career Option after 10+2
Career Option after 10+2
 
Bubble Sort
Bubble SortBubble Sort
Bubble Sort
 
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMINGChapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
Chapter 3 INSTRUCTION SET AND ASSEMBLY LANGUAGE PROGRAMMING
 

Similar to Operating Systems - Intro to C++

Operating Systems - Queuing Systems
Operating Systems - Queuing SystemsOperating Systems - Queuing Systems
Operating Systems - Queuing Systems
Emery Berger
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - Concurrency
Emery Berger
 
Operating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingOperating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel Computing
Emery Berger
 
Brian Oliver Pimp My Data Grid
Brian Oliver  Pimp My Data GridBrian Oliver  Pimp My Data Grid
Brian Oliver Pimp My Data Grid
deimos
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced Synchronization
Emery Berger
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Volha Banadyseva
 
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia "What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
Vladimir Ivanov
 

Similar to Operating Systems - Intro to C++ (20)

Processes and Threads
Processes and ThreadsProcesses and Threads
Processes and Threads
 
Operating Systems - Queuing Systems
Operating Systems - Queuing SystemsOperating Systems - Queuing Systems
Operating Systems - Queuing Systems
 
Operating Systems - Concurrency
Operating Systems - ConcurrencyOperating Systems - Concurrency
Operating Systems - Concurrency
 
Operating Systems - Virtual Memory
Operating Systems - Virtual MemoryOperating Systems - Virtual Memory
Operating Systems - Virtual Memory
 
Operating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel ComputingOperating Systems - Distributed Parallel Computing
Operating Systems - Distributed Parallel Computing
 
Reconsidering Custom Memory Allocation
Reconsidering Custom Memory AllocationReconsidering Custom Memory Allocation
Reconsidering Custom Memory Allocation
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Simulation lab
Simulation labSimulation lab
Simulation lab
 
Memory Management for High-Performance Applications
Memory Management for High-Performance ApplicationsMemory Management for High-Performance Applications
Memory Management for High-Performance Applications
 
Reproducible Linear Algebra from Application to Architecture
Reproducible Linear Algebra from Application to ArchitectureReproducible Linear Algebra from Application to Architecture
Reproducible Linear Algebra from Application to Architecture
 
H2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt DowleH2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt Dowle
 
Brian Oliver Pimp My Data Grid
Brian Oliver  Pimp My Data GridBrian Oliver  Pimp My Data Grid
Brian Oliver Pimp My Data Grid
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced Synchronization
 
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpotВладимир Иванов. Java 8 и JVM: что нового в HotSpot
Владимир Иванов. Java 8 и JVM: что нового в HotSpot
 
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia "What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
"What's New in HotSpot JVM 8" @ JPoint 2014, Moscow, Russia
 
Scala Sjug 09
Scala Sjug 09Scala Sjug 09
Scala Sjug 09
 
ICIAM 2019: Reproducible Linear Algebra from Application to Architecture
ICIAM 2019: Reproducible Linear Algebra from Application to ArchitectureICIAM 2019: Reproducible Linear Algebra from Application to Architecture
ICIAM 2019: Reproducible Linear Algebra from Application to Architecture
 
Reverse Engineering Malicious Javascript
Reverse Engineering Malicious JavascriptReverse Engineering Malicious Javascript
Reverse Engineering Malicious Javascript
 
Operating Systems - Networks
Operating Systems - NetworksOperating Systems - Networks
Operating Systems - Networks
 

More from Emery Berger

Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic Multithreading
Emery Berger
 
Programming with People
Programming with PeopleProgramming with People
Programming with People
Emery Berger
 
Stabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationStabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance Evaluation
Emery Berger
 
Operating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsOperating Systems - Advanced File Systems
Operating Systems - Advanced File Systems
Emery Berger
 
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Emery Berger
 

More from Emery Berger (18)

Doppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language BarrierDoppio: Breaking the Browser Language Barrier
Doppio: Breaking the Browser Language Barrier
 
Dthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic MultithreadingDthreads: Efficient Deterministic Multithreading
Dthreads: Efficient Deterministic Multithreading
 
Programming with People
Programming with PeopleProgramming with People
Programming with People
 
Stabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance EvaluationStabilizer: Statistically Sound Performance Evaluation
Stabilizer: Statistically Sound Performance Evaluation
 
DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)DieHarder (CCS 2010, WOOT 2011)
DieHarder (CCS 2010, WOOT 2011)
 
Operating Systems - Advanced File Systems
Operating Systems - Advanced File SystemsOperating Systems - Advanced File Systems
Operating Systems - Advanced File Systems
 
Operating Systems - File Systems
Operating Systems - File SystemsOperating Systems - File Systems
Operating Systems - File Systems
 
Operating Systems - Synchronization
Operating Systems - SynchronizationOperating Systems - Synchronization
Operating Systems - Synchronization
 
Virtual Memory and Paging
Virtual Memory and PagingVirtual Memory and Paging
Virtual Memory and Paging
 
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained EnvironmentsMC2: High-Performance Garbage Collection for Memory-Constrained Environments
MC2: High-Performance Garbage Collection for Memory-Constrained Environments
 
Vam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory AllocatorVam: A Locality-Improving Dynamic Memory Allocator
Vam: A Locality-Improving Dynamic Memory Allocator
 
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory ManagementQuantifying the Performance of Garbage Collection vs. Explicit Memory Management
Quantifying the Performance of Garbage Collection vs. Explicit Memory Management
 
Garbage Collection without Paging
Garbage Collection without PagingGarbage Collection without Paging
Garbage Collection without Paging
 
DieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe LanguagesDieHard: Probabilistic Memory Safety for Unsafe Languages
DieHard: Probabilistic Memory Safety for Unsafe Languages
 
Exterminator: Automatically Correcting Memory Errors with High Probability
Exterminator: Automatically Correcting Memory Errors with High ProbabilityExterminator: Automatically Correcting Memory Errors with High Probability
Exterminator: Automatically Correcting Memory Errors with High Probability
 
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
Exploiting Multicore CPUs Now: Scalability and Reliability for Off-the-shelf ...
 
Composing High-Performance Memory Allocators with Heap Layers
Composing High-Performance Memory Allocators with Heap LayersComposing High-Performance Memory Allocators with Heap Layers
Composing High-Performance Memory Allocators with Heap Layers
 
CRAMM: Virtual Memory Support for Garbage-Collected Applications
CRAMM: Virtual Memory Support for Garbage-Collected ApplicationsCRAMM: Virtual Memory Support for Garbage-Collected Applications
CRAMM: Virtual Memory Support for Garbage-Collected Applications
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Operating Systems - Intro to C++

  • 1. Operating Systems CMPSCI 377 C/C++ Emery Berger University of Massachusetts Amherst UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science
  • 2. Why C? UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 2
  • 3. Why C? Low-level  Direct access to memory  WYSIWYG (more or less)  Effectively no runtime system  No garbage collector  No other threads  No “read” or “write barriers”  Efficient  Space & time  C: effectively portable assembly code  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 3
  • 4. OK, Why C++? UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 4
  • 5. OK, Why C++? C++: extends C  Upwardly-compatible  Adds significant software engineering  benefits Classes  Encapsulation (private)  Templates (“generics”)  Other modularity advantages  Inlining instead of macros  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 5
  • 6. Outline, part I Basics – compiling & running  Intrinsic types, conditionals, etc.  Pointers + Reference variables  Assignment  Objects  &, *, ->  Stack vs. heap  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 6
  • 7. Outline, part II Functions  Parameter passing  Structs & classes  Overloading & inheritance  Stack vs. heap  I/O, command-line  STL  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 7
  • 8. Basics Main & compilation  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 8
  • 9. Intrinsic Types Essentially identical  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 9
  • 10. Conditionals Mostly the same  C/C++: nonzero int same as true  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 10
  • 11. File I/O Simple stream-based I/O  print foo cout << “foo”  read x from the console cin >> x  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 11
  • 12. Command-line Arguments Again, similar to Java  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 12
  • 13. Key Differences Differences between C/C++ and Java  Assignment  Pointers  Parameter passing  Heap & Stack  Arrays  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 13
  • 14. Assignment Java assignment: makes reference  C++ assignment: makes copy  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 14
  • 15. Pointers & Friends Pointers are like jumps, leading wildly from  one part of the data structure to another. Their introduction into high-level languages has been a step backwards from which we may never recover. C.A.R. Hoare UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 15
  • 16. Pointers & Friends Concept not in Java: address manipulation  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 16
  • 17. Functions & Parameter Passing C/C++ – all parameters copied by default  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 17
  • 18. Parameter Passing To change input, pass pointer  or call by reference UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 18
  • 19. Pass by Reference Syntactic sugar:  foo (int &i) = pass by reference Secretly does pointer stuff for you  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 19
  • 20. Stack & Heap UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 20
  • 21. Stack & Heap In C/C++ as in Java, objects can live on  stack or on heap Stack = region of memory for temporaries  Stack pointer pushed on function entry  Popped on function exit  Heap = distinct region of memory for  persistent objects C/C++ – explicitly managed  Pointers introduce problems!  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 21
  • 22. The Stack Stack data: new every time  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 22
  • 23. Big Stack Mistake Never return pointers to the stack!  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 23
  • 24. The Heap Allocate persistent data on heap with new  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 24
  • 25. Explicit Memory Management Java heap – garbage collected  C/C++ – explicit memory management  You must delete items (or memory leak)  Delete them too soon (still in use) – crash  “Dangling pointer” error  Delete something twice – crash  “Double-free” error  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 25
  • 26. Classes & Objects No “top” object (as in Java Object)  Also: C++ has no interfaces but has multiple  inheritance – stay far away Key difference for you – not all methods  dynamically-dispatched Methods associated with declared type  rather than dynamic type unless labeled virtual UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 26
  • 27. Struct Member Access struct = class with everything public  Use these sparingly  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 27
  • 28. Class Declaration Pretty similar  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 28
  • 29. Arrays Numerous differences  Arrays do not have to be allocated with new  Array bounds not checked  Item[0] = pointer to start of array  Arrays just syntactic sugar  for pointer arithmetic! (scary! avoid!) v = 12; *(Item + v) = 1;  Same as Item[12] = 1;  Note: sizeof(x) = number of bytes to hold x  Multi-dimensional arrays (matrices)  just arrays of pointers to arrays  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 29
  • 30. Other Features Operator overloading  New meanings to existing operators  int operator+(MyType& a, MyType& b);  Controversial, but useful for things like  complex math, matrix operations int& operator()(int x, int y);  Templates  A.k.a. generics in Java  template <class X> void foo (X arg);  UNIVERSITY OF MASSACHUSETTS AMHERST • Department of Computer Science 30