faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/proglanguages/vari… · web viewjava author...

29
Variable Names, Scope & Types Terms when using variables What are some terms you think of when we discuss variables? 1. Scope 2. Naming 3. Type.. (duh) 4. But what else? What other terms are important when discussion variables? Names Names refer to different kinds of entities in programs, such as variables, functions, classes, templates, modules, . . . . Names can be reserved or user-defined Names can be bound statically or dynamically Name bindings have a scope: the program area where they are visible Exercise with Example C++ can be any length, but often only the first 2048 characters are significant name cannot be a number 1

Upload: others

Post on 19-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Variable Names, Scope & Types

Terms when using variables What are some terms you think of when we discuss variables?1. Scope2. Naming3. Type.. (duh)4. But what else? What other terms are important when discussion variables?

Names Names refer to different kinds of entities in programs, such as variables,

functions, classes, templates, modules, . . . . Names can be reserved or user-defined Names can be bound statically or dynamically Name bindings have a scope: the program area where they are visible

Exercise with ExampleC++

can be any length, but often only the first 2048 characters are significant name cannot be a number

o int 100; // ERRORo name must start with a letter or a “_” (underscore)o name could contain numbers

int laneNumber2; variable names ARE VERY CASE SENSITIVE!!! NO SPACES OR SPECIAL CHARACTERS!!!

1

Page 2: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

List the Differences from C++ about NAMING variablesR

PHPPerlJavaScript

Visual Basic

Scheme

Variable Declaration Essentially, variables are bindings of a name to a memory address They also have a type, value, scope, and lifetime Bindings can be

o dynamic (occur at run time), or o static (occur prior to run time)

a new name for an existing type is a type declarationo a new name for a new type is defined by specific its values using a data

declaration building new custom objects using a class construct go over more in Java

const int d = 400; void f() { double d = 100;{ double d = 200; std::cout << d;} std::cout << d; } double g() { return d+1;}

How Java and C++ set up their variables is also different!! (Next page)

2

Page 3: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Initialized Variables?C++#include <iostream>#include <string>using namespace std;

int main(){

cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

int x;string y;float z;

cout << "x is: " << x << endl;cout << "y is: " << x << endl;cout << "z is: " << x << endl;

return 0;}!!!Hello World!!!x is: 4201216y is: 4201216z is: 4201216

Java

Notice class variables are auto initialized, but not non-class.

3

Page 4: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Variable types primitives

o ints, float, Boolean, etc…o one language may not have a primitive that another does.

Wrapperso covered later

Customo objects built up of other datatypes

size of the same types between languages can vary!!

Fill in the table below of the sizes of each data type:C++ Java

ShortIntLonglong longFloatDoublelong doubleHow big can Java’s BigInteger get?How does Java handle unsigned?

4

Page 5: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Scope/Jurisdiction Scope is a property of a name binding The scope of a name binding are the parts of a program (collection of

statements, declarations, or expressions) that can access that binding Static/lexical scoping

o Binding’s scope is determined by the lexical structure of the program (and is thus known statically)

o The norm in most of today’s languageso Efficient lookup: memory location of each variable known at compile-

timeo Scopes can be nested

inner bindings hide the outer ones

Example of Jurisdiction MANY of you understand

In MARYLAND!!! (Apparently not in Texas!!)

5

Federal

State Police

County Police

Town Police

Campus PoPo

Page 6: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

What are the scopes of names here, when are variables bound to types and values, and what are their scopes?

1. ID each variable2. Determine their original value3. Do the values change?4. What is the scope of each variable

Scope and Lifetime Exercise#include <iostream>const int d = 400;

void f(){ double d = 100; { double d = 200; std::cout << d << "\n";} // this is NOT an error std::cout << d << "\n";}

double g() { return d+1;}

int main(){ f(); std::cout << g() << "\n"; return 0;}

5. Try it out to prove if you are correct!a. Can use https://www.onlinegdb.com/online_c++_compiler

6

Page 7: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Static/Lexical Scoping & Binding also called static scoping

o static since values are deduced at compile time convention used with many programming languages that sets the scope

(range of functionality) of a variable so that it may only be called (referenced) from within the block of code in which it is defined

in shorto inner level can access its outer levels

Please don’t do this… but it’s an example

namespace std { ... }

namespace N { void f(int x) {};

class B { void f (bool b) { if (b) { bool b = false; // confusing but OK std::cout << b; } } };}

7

Page 8: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

But if static, might not be consistent!!C++ JavaDoes this work in C++?? Code it!

Does this work in C++?? Code it!

This SHOULD work in C++

8

Page 9: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Copy, Paste, and run the Scheme code found here:http://faculty.cse.tamu.edu/slupoli/notes/Scheme/code/lexicalScoping/example1.txt

1. remember this is an example static scopinga. what does it mean to be static?

2. Make sure to understand WHY the results came out like they did!!

9

Page 10: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Dynamic Scoping Some early versions of LISP have dynamic scoping

o older languages Variable’s binding is taken from the most recent declaration encountered in

the execution path of the programo the outer scope depends on the chain of calls from functionso using this scoping rule, we first look for a local definition of a variableo if it isn't found, we look up the calling stack for a definition

Macro expansion of the C preprocessor gives another example of dynamic scoping

Makes reasoning difficult, since it is not consistent

Where Dynamic Scoping can be difficultExample 1// Since dynamic scoping is very uncommon in the familiar languages, we // consider the following pseudo code as our example.// It prints 20 in a language that uses dynamic scoping.int x = 10;

int f() { return x; }// Called by g()

int g() // g() has its own variable named as x and calls f(){   int x = 20;   return f();}

main(){  printf(g()); // would print 20 if dynamic!// Why? Which variable was used last?}

Example 2#define ADD_A(x) x + a // who know what “a” could really be!

void add_one(int *x){ const int a = 1; x = ADD_A(x);}

10

Page 11: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

void add_two(int *x) { const int a = 2; x = ADD_A(x); }

11

Page 12: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

l- and r-valuesa = b;

“place” “thing”

// that’s why we read right to left // so our statement above would read “Put the “thing” into this “place””

[lvalue] = [rvalue]; // sure you’ve seen that error before

lvalue is our PLACE, must be defined and definite (that’s why “a+1 = b + 3;” will not work)

rvalue is our THING, can be anything to complete the statement or equation when we assign ANYTHING to a variable, we use a variable name to access

the memory that holds that data Depending on the context, a variable can denote the address (l-value), or the

value (r-value)

int x; x = x + 1;

Some languages distinguish between the syntax denoting the value and the address, e.g., in ML

x := !x + 1

From type checking perspective, l- or r-“valueness” is part of the type of an expression

12

Page 13: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Lifetime Time when a variable has memory allocated for it Scope and lifetime of a variable often go hand in hand A variable can be hidden, but still alive

Hidden Variable Examplevoid f (bool b){ if (b) { bool b = false; // hides the parameter b std::cout << b; }}

A variable can be in scope, but not alive (without value)o wasted memory!!

It’s (still) alive!!#include <iostream>using namespace std;

int main(){ cout << "Hello World" << endl;

int* a = new int(23); int& aref = *a; delete a; cout << "But the value is still there!! " << aref << endl; // aref should be set to null!!

return 0;}// aref is not alive, but in scope

Draw this out!! See why “aref” is dead.

13

Page 14: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Variable-Type Binding Types can be bound to variables statically or dynamically

Variable-Type BindingStatic

string x = “Hi”;x = 1.2; // error// Static binding may or may not require annotationsx = 23;x++;

Dynamicstring x = “Hi”;x = 1.2; // OK

Determine which languages allow static/dynamic.

Allow Static Allow Dynamic

14

Page 15: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Types and Type Systems Data typing is a mechanism by which a program tells the compiler or

interpreter how the data will be used Type defines and constrains how the data may be stored and what operations

may be performed on the data This allows a compiler to check for type errors, which helps to ensure that a

program is free of errors Types are collections of values (with operations that can apply to them) At the machine level, values are just sequences of bits Is this 0100 0000 0101 1000 0000 0000 0000 0000

o floating point number 3.375? o integer 1079508992? o two short integers 16472 and 0? o four ASCII characters @ X NUL NUL?

Programming at machine-level (assembly) requires that programmer keeps track of what are the types of each piece of data

Type errors (attempting an operation on a data type for which the operation is not defined) hard to avoid

Goal of type systems is to enable detection of type errors o reject meaningless programs

Pick one language, determine the types it has.

15

Page 16: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Languages w/ some type system, but unsound C, C++, Eiffel Reject most meaningless programs:

int i = 1; char* p = i;

but allow some

Unsound type systems

union { char* p; int i;} my_union;

void foo(){ my_union.i = 1; // ok here char* p = my_union.p; // iffy here . . .}

and deem the behavior undefined – just let the machine run and do whatever

16

Page 17: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Sound Type System Java and Haskell Reject some meaningless programs at compile-time:

int i = “Erroneous”;

Add checks at run-time so that no program behavior is undefined

Sound Type System example

interface Stack{ void push(Object elem); Object pop();}class MyStack { . . . }

Stack s = new MyStack();s.push(1);s.push(”whoAreYou…”);int i = (Int) s.pop(); // throws an exception // since it should have been a string!

Dynamic (but Sound) Type System Scheme, Javascript Reject no syntactically correct programs at compile time, types are enforced at

run-time:

; car – access 1st item in list; con – constructs a list

(car (cons 1 2)) ; ok, 1(car 5) ; error at run-time

Straightforward to define the set of safe programs and to detect unsafe ones

17

Page 18: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Type Systems Common errors

o examples of operations that are outlawed by type systems Add an integer to a function Assign to a constant Call a non-existing function Access a private field

Type systems can helpo in early error detectiono in code maintenanceo in enforcing abstractionso in documentationo in efficiency

18

Page 19: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Type Systems Terminology Static vs. dynamic typing

o Whether type checking is done at compile time or at run time Strong vs. weak typing

o Sometimes means no type errors at run time vs. possibly type errors at run time (type safety)

o Sometimes means no coercions vs. coercions (implicit type conversion)o Sometimes even means static vs. dynamic

Type inferenceo Whether programmers are required to manually state the types of

expressions used in their program or the types can be determined based on how the expr’s are used

o E.g., C requires that every variable be declared with a type; Haskell infers types based on a global analysis

Type Checking in Language Implementation Get into later with Grammar/Parsing/Syntactic Analysis

How type checking fits in

Answers19

Page 20: faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/ProgLanguages/Vari… · Web viewJava Author Lupoli, Shawn V Created Date 09/09/2019 15:37:00 Last modified by Lupoli, Shawn

Scope Exercise200100401

SourcesDr. Dylan Shell CSCE 314 Notes

Lexical/Static Scopehttps://stackoverflow.com/questions/1047454/what-is-lexical-scope https://whatis.techtarget.com/definition/lexical-scoping-static-scoping https://courses.cs.washington.edu/courses/cse341/14wi/general-concepts/scoping.html

20