Partial Functions, Blocks, Scope, Lifetime, & Memory Allocation - Programming Languages - Sept 17th, 2019
Similar to mathematics, not every input needs to have an output. For example, the code below does not have a return value when given an empty list
mylast :: [a] -> a
-- mylast [] = []
mylast [x] = x
mylast (x : xs) = mylast xsVariables are usually defined in blocks, but can also be defined in:
- the global scope
- namespaces
- structs
int x;
namespace Foo {
	int qwaptu = 4;
}
struct Whatever {
	string z;
}
int foo(){ // first block
	int x = 3;
	while (x > 0) { // second block 
		x-=1
	}
}The region of a program over which a binding is maintained
What will be printed in the following C++ code?
Code 1.1
int x = 3;
void foo() {
	print(x);
	x = 9;
}
int main() {
	int x = 0; // shadow
	foo();
	print(x);
	return 0;
}Answer
3 and 0When two variables with same name are defined in overlapping scopes, then one variables shadows another variable.
In C++, we could refer to the global x by writing ::x. :: is the scope operator in C++.
C++, C, Python, and Java use static scoping which means you know the scope of your variables and functions before you run your program
Functions have the same scope as where they were called from. Dynamic Scoping is almost like copying and pasting the body of a function wherever it is called.
What would the same code from before print if it was using dynamic scoping?
Answer:
0 and 9int x = 3;
void foo() {
	print(x);
	x = 9;
}
int main() {
	int x = 0; // shadow
	foo();
	print(x);
	return 0;
}#include <stdio.h>
int x = 1;
char y = 'a';
void p() {
	double x = 2.5;
	printf("%c \n", y);
	{ int y[10]; }
}
void q() {
	int y = 42;
	printf("%d \n", x);
	p();
}
main() {
	char x = 'b';
	q();
	return 0;
}Answer:
1 and βaβAnswer:
98 and '*'This is because the `printf` statements include conversions between char and double.
int main(){
	int *x = new int(0);
	delete x;
	return 0;
}Lifetime: the duration for which a variable has memory allocated for it
Types of Memory Allocation:
- Automatic (Stack) Allocation
- defining a variable inside a function
 
- Dynamic Allocation
- ex: using newin C++
 
- ex: using 
- Static Allocation
- ex: global variable
- In C++, you can define a variable with the keyword staticinside a function as well- The lifetime of a static variable is the same as a global variable
- The scope of the static variable is still local
 
 
void incprint() {
	static int x = 0;
	print (x);
	x++;
}
int main(){
	incprint(); // prints 1
	incprint(); // prints 2 
	incprint(); // prints 3
	return 0;
}What does this program print?
int *bar() {
	int i = 99;
	return &i;
}
int main() {
	int *z = bar();
	print(*z);
	return 0;
}Answer:
This program has a bug because you are trying to print `i` which now points to a deallocated space in memory
int x = 3;
void barf() {
	int c;
	foo();
}
void foo() {
	print(x);
	x = 9;
}
int main() {
	foo();
	int x = 0;
	barf();
	print(x);
	return 0;
}#proglang-f19