Types and variables

advertisement
CS351 – Week 1
Topics
• Native Types
• Memory representation
• Variable initialization declaration and
allocation
Previous knowledge
• How to select variable type (string, integer, float, or
boolean)
• Concept of capturing external files for use in
programming (import or include)
• Reading strings from standard input and parsing for
numeric types if needed
• Converting and concatenating strings for output to
screen
• Compute and save numerical results
• Understanding of how to use a randomize function
Objectives
• Identify native types in C++ that are generally available
• Understand how to declare, allocate and initialize a
variable
• Declare variables in global or local scope
• Create a basic C++ program that takes input from
standard in, computes a value and prints the value to
the screen
–
–
–
–
Using constant values
Appropriately including needed files
Correctly coding the main signature
Using object for inputting and outputting values
Including files
• Reusing code from a library
– Python
–C
import math
#include <math.h>
• Differences between C and Python?
• How do you find what file has the function
you want?
Computer memory
Conceptually the memory in a computer is very much like building lots laid
out by lot number on a map of the streets of a city before any houses have
been built.
Computer memory
Lots can be used individually or as groups
Although memory has a basic unit, units can be used together to represent
more complex data
Data for variables
•
•
•
•
•
“Jane Doe”
$475.24
123-45-6789
26 years of age
January
Native types in C++
• char – typically holds data encoded to represent written
character sets
• integer types – whole numbers; can be signed or unsigned;
variations represent integers that use from 8 bits to 64 bits
• float types – Stores numbers as fraction, exponent and
sign; not precise
• boolean – true or false
• Reference (pointer) – location that refers to another
location
• strings – usually as array of characters; have special
handling in the language; variable name refers to first
location
Size of types is implementation dependent
Resources: http://en.wikipedia.org/wiki/Primitive_data_type,
http://www.cplusplus.com/doc/tutorial/variables/
wget http:/bama.ua.edu/~anderson/size.cc
Sample program
//size.cc
#include <iosteam>
using namespace std;
int main() {
Needed for
cout and endl
Like java packages
Will discuss later
cout<<“sizeof(int) is ”<<sizeof(int)<<“ bytes”<<endl;
return 0;
}
String literal
sizeof give the size in
bytes of a type or
variable
Needed since sizes vary
** What are the non-reserved words?
Sample program
//size.cc
#include <iosteam>
using namespace std;
int main() {
cout<<“sizeof(int) is ”<<sizeof(int)<<“
bytes”<<endl;
return 0;
}
Other general rules
• Everything is case sensitive
• These identifiers are
reserved (can’t be used as
variable names)
What does it mean to be a
reserved word?
http://en.cppreference.com/w/cpp/keyword
Other syntax
• semicolons are used to denote the end of a statement
except
– after the #include statement
– before a block
• Whitespace is not part of syntax
//size.cc
#include <iosteam>
using namespace std;
int main() {
cout<<“sizeof(int) is ”<<sizeof(int)<<“ bytes”<<endl;
return 0;
}
Programmed Example - 10 min
Work in pairs (only pairs)
• Create a C++ program that prints out the size of the following variables
–
–
–
–
–
–
–
–
char
int
unsigned int
short
long
long long
float
double
• Fix w1ex1.cc so that it compiles and prints Hello World
Turning in programs
Put both names at top
Comments start with //
cat <program name> |mailx –s “<lastname 1> <lastname2> Week # Date” cs351@cs.ua.edu
Example:
cat w1ex1.cc |mailx –s “hong anderson Week 1 011414” cs351@cs.ua.edu
User input form keyboard
//cin.cc
#include <iosteam>
using namespace std;
int main() {
int value;
cin >>value;
cout<<“The user entered” <<value<<endl;
cout<<“value * 3 ==<<” <<value*3<<endl;
return 0;
}
1st assignment – 5 min
Work in pairs (only pairs)
• Fix w1ex2.cc so that it calculates the user’s mileage
reimbursement
Turning in programs
Put both names at top
Comments start with //
cat w1ex2.cc|mailx –s “Week 1: 011414” cs351@cs.ua.edu
C++ variables
• Declaration – Give variable a name and a type
• Allocation – Identify location where variable
will be stored
• Initialization – Set variable to appropriate
initial value
When this happens depends on scope…
Variable scope
• A scope is a region of the program and broadly
speaking there are three places, where
variables can be declared:
– Inside a function or a block which is called local
variables,
– In the definition of function parameters which is
called formal parameters.
– Outside of all functions which is called global
variables.
C++ native type rules
• For local variables
– <type> <identifier>; will only declare and allocate
– <type> <identifier>=<value>; will declare, allocate
and initialize
Local variable declaration
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
C++ native type rules
• For global declarations
– <type> <identifier>; will declare, allocate and
initialize
– <type> <identifier>=<value>; will declare,
allocate and initialize
Mixed declaration
//mixed.cc
#include <iostream>
using namespace std;
int g;
int main () {
// Local variable declaration/allocation:
int a, b;
cout <<a; //not guaranteed to be coherent
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Same variable in two scopes
//twoscopes.cc
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
Is this an error? If not, what prints here?
cout << g;
return 0;
}
The enclosing scope has precedence
Variable scope matters
• If the scope of a variable is global (defined outside of
braces),
– Can be used throughout a program (any function or code; even
in other source files
– Memory is know to be needed at compile time
– Compiler can designate a place for this memory as part of the
program setup
• If a variable has scope local to some block
– it can only be used by statements in that block
– compiler knows about it *but* we don’t know when functions
will be run;
– To conserve memory, we reused the memory when it is not
needed (out of scope)
Memory in these two different cases are allocated in
different places in the process space (program)
C++ constants
• Uses const modifier in front of variable
declaration
• Value cannot be changed (compiler code will not
be generated)
• Allows compiler to optimize access
• Acts as a semantic check
• Better than #define because the type is specified
(allows type checking by compiler)
• #define is a macro; replaces text before compiling
Constants
//const.cc
#include <iostream>
using namespace std;
// Global variable declaration:
const int monthsInYear = 12;
int main () {
cout<<monthsInYear<<endl;
int age;
cin>>age; //what happens if you put in a floating poitn number?
cout<<“Entered age “<<age<<endl;
monthsInYear=0; //error line
int totalMonths = monthsInYear*age;
count<<totalMonths<<endl;
return 0;
}
C++ reference types
• Strings, objects, arrays, and structures are not
native types but are reference types
• Composed of primitive types
• Different rules for declaration, allocation and
initialization
• For all types, if you initialize, you automatically
allocate
2nd Assignment
• Fix w1ex3.cc so that it:
– prints prompts for user input
– prints out the number of weeks in the current month
– Calculates the current weekly salary based on monthly
salary input and weeks in the current month
• Write a program that takes an angle in degrees
from the user and converts it to radians. Use a
constant for π
• Consult instructions for submission
• Quiz online on this material posted Monday;
complete before class on Tuesday
Download