1 / 198

C++ Training Datascope Lawrence D’Antonio

C++ Training Datascope Lawrence D’Antonio. Lecture 9 An Overview of C++: What is Typing?. Type Systems. “The purpose of a type system is to prevent the occurrence of execution errors during the running of a program.” Cardelli

ivie
Download Presentation

C++ Training Datascope Lawrence D’Antonio

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ TrainingDatascopeLawrence D’Antonio Lecture 9 An Overview of C++: What is Typing?

  2. Type Systems “The purpose of a type system is to prevent the occurrence of execution errors during the running of a program.” Cardelli The largest allowed range of values for a program variable is its type. Languages in which variables have non-trivial types are called typed languages.

  3. Type Systems 2 Languages that do not restrict the ranges of variables are called untyped languages. The -calculus is an example of an untyped language. Languages can check for type errors either during compile time (static checking) or run-time (dynamic checking).

  4. Type Systems 3 There are two types of execution errors. Errors that cause computation to stop are called trapped errors. Errors that go unnoticed and cause arbitrary behavior are called untrapped errors. A program is safe if it does not cause untrapped errors to occur.

  5. Type Systems 4 Languages in which programs are safe are called safe languages.

  6. Types of typing • Static typing: Data type determined at compile-time. Type must be declared or inferred. • Dynamic typing: Data type may be determined at run-time. Type need not be declared. • Strong typing: Variables are bound to a specific type. • Weak typing: A variable’s type may change.

  7. Types of typing 2 • Soft typing: Type checking occurs, but incorrect types are only given warnings. • Manifest typing: Types are named explicitly in the code.

  8. Varieties of typing • Static and strong typing: Java, Pascal, OCaml, Haskell • Static and weak typing: C/C++ • Dynamic and strong typing: Python • Dynamic and weak typing: PHP

  9. Type Systems • Is there a nontrivial type associated with each declaration? • Static typing = yes, Dynamic typing = no, Soft typing = optional • If there is, are these types declared explicitly in the source code? • Manifest typing = yes, Type Inference = optional

  10. Type Systems 2 • Does the possibility of a type failure cause a compile-time error? • Static typing = yes, Dynamic or soft typing = no • Is the type system strictly enforced, with no loopholes or unsafe casts? • Strongly typed = yes, Weak typing = no

  11. Benefits of a Type System • Safety: The use of a type system allows the compiler to detect invalid or meaningless code. For example, the code x = 5/”Hello” • will be caught as illegal.

  12. Benefits of a Type System 2 • Optimization: a compiler can use type information in various ways to improve a program. • For example, knowing values of a certain type must align at a multiple of 4 may let the compiler use more efficient machine instructions. • Also, a type system allows the compiler to select appropriate code.

  13. Benefits of a Type System 3 • Documentation: the use of type can be documentation of the programmer’s intent. • Type annotation documents how program objects are to be used.

  14. Benefits of a Type System 4 • Abstraction: the ability to name types allows the programmer to think about programs at a higher level. • The hiding of type details lets the programmer directly model the problem domain. • The correctness of a program does not depend on the implementation of types.

  15. Static typing • Also known as early binding. • Under static typing, the method to be called is the one associated with the type of the formal parameter. • The binding can occur as soon as the type of the formal parameter is known. • C++ uses static typing by default.

  16. Static typing 2 • A reference value is a program construct that is a value and can have a value. It can have different values at different times. • In static typing a reference is constrained with respect to the type of value denoted by the reference. • In a statically typed language one relies upon the compiler to do type checking.

  17. Static typing 3 • There are two ways to implement static typing. • One method is type inference. Here the type of an expression is inferred through analysis of the program. • Another method is manifest typing. Here objects must be declared with a type annotation.

  18. Type inference • Many languages use type inference exclusively or in part. For example, the languages Boo, C# 3.0, Cayenne, Chrome, Clean, Cobra, D, Epigram, F#, Haskell, ML, Nemerle, OCaml, Scala use type inference.

  19. Type inference 2 • C# 3.0 example var x = “Hello”; //x is deduced to be a string //More complex example var custQuery = from cust in customers where cust.City == "Phoenix" select new { cust.Name, cust.Phone };

  20. Type inference 3 • Boo example. The type of an array is the least generic type that could store all elements in the array. a = (1, 2) # a is of type (int) b = (1L, 2) # b is of type (long) c = ("foo", 2) # c is of type (object)

  21. Type inference 4 • Haskell example • apply f v = f v • The inferred type for apply is • (a -> b) -> a -> b • Namely apply is a function that takes a function taking an argument of type a and returning a value of type b and applies the function to the argument, returning a b.

  22. Type inference 5 • C++ uses type inference. • For example, template parameters are deduced from the argument types in a function call.

  23. Type inference 6 • C++ ‘09 will have a greater use of type inference. For example: for(auto p = v.begin(); p! = v.end(); ++p) cout << *p << endl;

  24. Type inference 7 • Chrome example var u := from u in lUsers where u.Age = 35 order by u.Name; • Here lUsers is a collection of objects of unnamed type.

  25. Type inference 8 • Cobra example class Foo def bar i = 1_000_000 for j = 0 .. i doSomething(j) def doSomething(i as int) pass

  26. Type inference 9 • F# example let asynctask = async { let req = WebRequest.Create(url) let! response = req.GetResponseAsync() use stream = response.GetResponseStream() use streamreader = new System.IO.StreamReader(stream) return streamreader.ReadToEnd() }

  27. Type inference 10 • Nemerle example def d = Dictionary (); d.Add ("Ala", 7); foreach (s in args) { ... }

  28. Dynamic typing • In dynamic typing, type checking normally occurs at run time. • Operations are checked just before they are performed. • For example, the code for the + operator may check the types of its operands just before the addition is performed.

  29. Dynamic typing 2 • For example, if the operands for the + operator are both integers then integer addition is performed. • If one operand is an integer and the other a floating point number then floating point addition is performed. • If one operand is an integer and the other a string then an exception is raised.

  30. Dynamic typing 3 • Dynamically typed languages are more flexible than statically typed languages. • The problem for statically determining for an arbitrary program whether or not a type error will occur at run time is undecidable. • Therefore sound static type checkers will determine some programs as potentially unsafe that would actually execute without a type error.

  31. Dynamic typing 4 • Static typing finds type errors at compile time. • Advocates of strongly statically typed languages such as ML and Haskell claim that most program errors are type errors. Namely, most errors would not occur if types were used in the correct manner by the programmer.

  32. Dynamic typing 5 • Static typing usually results in compiled code that executes more quickly than dynamic typing. • On the other hand, dynamic typing can reduce compile time and speed up the software development cycle.

  33. Dynamic typing 6 • Metaprogramming is the ability of a computer program to use or manipulate other programs (including itself) as its data. • Dynamic typing usually makes metaprogramming easier. For example, templates in C++ are more cumbersome than equivalent code in Python or Ruby.

  34. Metaprogramming • Metaprogramming is a facility provided by many languages. • Programs in Lisp, Python, Ruby, Smalltalk, PHP, REBOL, Perl, Tcl, Lua, and JavaScript are modifiable at run time. • The language of a metaprogram is called its metalanguage.

  35. Metaprogramming 4 • The ability of a programming language to be its own metalanguage is called reflection. • Other types of metaprogramming include: • Generative programming which involves one program generating another. • A quine which is a program that outputs itself.

  36. Metaprogramming 5 • Forth which is a self-compiling language. The programmer can modify the compiler. • A compiler is an example of a metaprogramming tool for translating high-level programs into machine code. • The compiler-compiler yacc is a metaprogramming tool to generate a tool for translating high level programs into machine code.

  37. Metaprogramming 6 • A quine in Atlas Autocode %BEGIN !THIS IS A SELF-REPRODUCING PROGRAM %ROUTINESPEC R R PRINT SYMBOL(39) R PRINT SYMBOL(39) NEWLINE %CAPTION %END~ %CAPTION %ENDOFPROGRAM~

  38. Metaprogramming 7 • Quine continued %ROUTINE R %PRINTTEXT ' %BEGIN !THIS IS A SELF-REPRODUCING PROGRAM %ROUTINESPEC R R PRINT SYMBOL(39) R PRINT SYMBOL(39) NEWLINE %CAPTION %END~ %CAPTION %ENDOFPROGRAM~ %ROUTINE R %PRINTTEXT ' %END %ENDOFPROGRAM

  39. Metaprogramming 8 • Quine example in C #include <stdio.h> int main(int argc, char** argv) { /* This macro B will expand to its argument, followed by a printf command that prints the macro invocation as a literal string */ #define B(x) x; printf(" B(" #x ")\n");

  40. Metaprogramming 9 • Quine C example continued /*This macro A will expand to a printf command that prints the macro invocation, followed by the macro argument itself. */ #define A(x) printf(" A(" #x ")\n"); x; /* Now we call B on a command to print the text of the program up to this point. It will execute the command, and then cause itself to be printed. */

  41. Metaprogramming 10 B(printf("#include <stdio.h>\n\nint main(int argc, char** argv)\n{\n/*This macro B will expand to its argument, followed by a printf\n command that prints the macro invocation as a literal string */\n#define B(x) x; printf(\" B(\" #x \")\\n\");\n\n/* This macro A will expand to a printf command that prints the macro invocation,\n followed by the macro argument itself. */\n#define A(x) printf(\" A(\" #x \")\\n\"); x;\n\n/* Now we call B on the text of the program\n up to this point. It will execute the command, and then cause\n itself to be printed. */\n"))

  42. Metaprogramming 11 A(printf("/* Lastly, we call A on a command to print the remainder of the program;\n it will cause itself to be printed, and then execute the command. */\n}\n")) /* Lastly, we call A on a command to print the remainder of the program; it will cause itself to be printed, and then execute the command. */ }

  43. Metaprogramming 12 • An extreme example of metaprogramming is language-oriented programming. • To solve a problem using language-oriented programming, one doesn’t use a general-purpose language. • Instead the programmer creates a domain specific programming language.

  44. Metaprogramming 13 • Two types of metaprogramming. • One: expose the internals of the run time engine through APIs. • Two: dynamic execution of strings containing program commands.

  45. Metaprogramming 14 • Metaprogramming example (in bash). #!/bin/bash # metaprogram echo '#!/bin/bash' >program for ((I=1; I<=992; I++)) do echo "echo $I" >>program done chmod +x program

  46. Ruby Example • Suppose we want to read a CSV file “people.txt” name,age,weight,height "Smith, John", 35, 175, "5'10" "Ford, Anne", 49, 142, "5'4" "Taylor, Burt", 55, 173, "5'10" "Zubrin, Candace", 23, 133, "5'6"

  47. Ruby Example 2 # file: my-csv.rb class DataRecord def self.make(file_name) data = File.new(file_name) header = data.gets.chomp data.close class_name = File.basename(file_name,".txt").capitalize # "foo.txt" => "Foo" klass = Object.const_set(class_name,Class.new) names = header.split(",")

  48. Ruby Example 3 klass.class_eval do attr_accessor *names define_method(:initialize) do |*values| names.each_with_index do |name,i| instance_variable_set("@"+name, values[i]) end end

  49. Ruby Example 4 • Still inside klass.class_eval define_method(:to_s) do str = "<#{self.class}:" names.each {|name| str << "#{name}=#{self.send(name)}" } str + ">" end alias_method :inspect, :to_s end

  50. Ruby Example 5 def klass.read array = [] data = File.new(self.to_s.downcase+".txt") data.gets # throw away header data.each do |line| line.chomp! values = eval("[#{line}]") array << self.new(*values) end data.close array end

More Related