Compsci 250 / ECE 250:
“C Programming”
Alvin R. Lebeck
Some slides based on those from Daniel Sorin,
Andrew Hilton, Amir Roth, Gershon Kedem
Administrivia
• Homework #1
• No class Monday
• Today
! Finish Data Representations
! C programming & Memory
• Updated Academic Honesty Policy
! Do not provide solutions to any archive (digital, paper, etc.)
! This is a simple extension of existing policy of not providing
solutions to another student.
Software Implication! Rounding Errors
• We only have 32-bits to represent floats
! Must approximate some values
•
•
•
•
Limited bits for mantissa
Does (x+y)*z = (x*z+y*z)?
Mathematically yes, but assumes infinite precision
Assume base 10, four digits available (two to left, two to
right of decimal point)
!
!
!
!
x = 99.96 x 103
x = x + 0.07
x = 100.03 x 103
x = 10.00 x 104
Need efficient representations
2’s complement for signed integers
IEEE Floating Point for Real numbers
Bits are bits are bits, same bits can be interpreted as
different types (unsigned, 2’s complement, float, etc.)
• Next up: C programming & memory
What you know today
• JAVA
...
System.out.println("Please Enter In Your First Name: ");
String firstName = bufRead.readLine();
System.out.println("Please Enter In The Year You Were Born: ");
String bornYear = bufRead.readLine();
System.out.println("Please Enter In The Current Year: ");
String thisYear = bufRead.readLine();
int bYear = Integer.parseInt(bornYear);
int tYear = Integer.parseInt(thisYear);
int age = tYear – bYear ;
System.out.println("Hello " + firstName + ". You are " + age + " years
old");
How does a Java program execute?
• Compile Java Source to Java Byte codes
• Java Virtual Machine (JVM) interprets/translates Byte
codes
• JVM is a program executing on the hardware…
• Java has lots of things that make it easier to program
without making mistakes
• JVM handles memory for you
! What do you do when you remove an entry from a hash table,
binary tree, etc.?
The C Programming Language
• No virtual machine
! No dynamic type checking, array bounds, garbage collection, etc.
! Compile source file directly to machine (this is a little simplified)
• Closer to hardware
! Easier to make mistakes
! Can often result in faster code
• Generally used for ‘systems programming’
! operating systems, embedded systems, database implementation
! There is object oriented C++ (C is a strict subset of C++)
The C Programming Language (Continued)
• No objects
• Procedural, not object oriented
! No objects with methods
• Structures, unions like objects
! Member variables (no methods)
•
•
•
•
Pointers – memory, arrays
External standard library – I/O, other facilities
Macro preprocessor (#<directive>)
Additional Resources
! Kernighan & Richie book The C Programming Language
! MIT open course Practical Programming in C link in ‘docs’ of web
site
! Drew Hilton Video Snippets
Use the gcc program to create an executable file
gcc –o <outputname> <source file name>
gcc –o hello hello.c (must be in same directory as hello.c)
If no –o option, then default output name is a.out (e.g., gcc hello.c)
Type the program name on the command line
! ./ before “hello” means look in current directory for hello program
Debugging
• Print debugging…
! Just output information at different points in the program
! Not the most efficient, but often works.
• gdb <executable filename>
• Good for stopping at set points in program and inspecting
variable values.
! If you get good at using a debugger it is easier/better than printf
debugging…
! See GDB Essentials video off https://www.cs.duke.edu/courses/
spring15/compsci250/docs.html
Variables, operators, expressions
• C variables are similar to Java
! Data types: int, float, double, char, void
! Signed and unsigned int
! char, short, int, long, long long can all be integer types
» These specify how many bits to represent an integer
• Constants
! Use #define C preprocessor
! E.g.,: #define MAX_SCORE 100
& operator performs bitwise AND
| operator performs bitwise OR
^ operator performs bitwise Exclusive OR (XOR)
~ operator performs bitwise NOT
• Per bit
0&0=0
0|0=0
0^0=0
0&1=0
0|1=1
0^1=1
1&0=0
1|0=1
1^0=1
1&1=1
1|1=1
1^1=0
• For multiple bits, apply operation to individual bits in same position
The SHIFT operator
• >> is shift right, << is shift left, operands are unsigned int
and number of positions to shift
• (1 << 3) is …000001 -> …0001000 (it’s 23)
• 0xff00 is 0xff << 8, and 0xff is 0xff00 >> 8
! Unsigned ints, be careful shifting signed integers (more later this
semester)
• 0xAB & 0x0F = 0x0B
• 0xAB & 0xF0 = 0xA0
• 0x0F and 0xF0 are called a bit mask
B.
xpos = val & 0x000ff;
ypos = (val & 0x0ff00) >> 8;
button = (val & 0x30000) >> 16;
D.
xpos = val & 0x000ff;
ypos = val & 0x0ff00 >> 1;
button = val & 0x30000 >> 2;
Precedence…shifts mask first; shift
amount wrong
Compsci / ECE 250
22
Functions
• Encapsulate computation
! Reuse or clarity of code
! Cannot define functions within functions
• Must be declared before use!
int div2(int x,int y); /* declaration here */
main() {
int a;
a = div2(10,2);
}
int div2(int x, int y) { /* implementation here */
return (x/y);
}
Global Variables
• Global variables: Accessible from any function
#include <stdio.h>
float f = 0;
void bar () {
f = 0.5;
}
int main()
{
f =0.31234;
bar();
printf(“The value is %f \n”, f);
}
Output is:
The value is 0.5
A Simple Program’s Memory Layout
...
int result; // global var
int main()
{
int x;
...
result = x + result;
...
}
For now, think of this as performing:
mem[0x208] = mem[0x400] + mem[0x208]
Sakai In Class Quiz 2.2
#include <stdio.h>
int a = 0;
float f = 0.5;
void setvals() {
float f = 0.5;
a = 78;
}
int main()
{
int a = 23;
f =0.31234;
setvals();
printf(“The values are %d, %f \n”,a,f);
}
a = 78, f = 0.5
a = 78, f = 0.31234
a = 23, f = 0.5
a = 23, f = 0.31234
27
Sakai In Class Quiz 2.2
#include <stdio.h>
int a = 0;
float f = 0.5;
void setvals() {
float f = 0.5;
a = 78;
}
int main()
{
int a = 23;
f =0.31234;
setvals();
printf(“The values are %d, %f \n”,a,f);
}
Reference vs. Pointer
Java
! “The value of a reference type variable, in contrast to that of a
primitive type, is a reference to (an address of) the value or set of
values represented by the variable” http://java.sun.com/docs/books/tutorial/java/
nutsandbolts/datatypes.html
! Cannot manipulate the value of the reference
C
! A pointer is a variable that contains the location of another
variable
! A pointer is a memory location that contains the address of
another memory location
! Can manipulate the value of pointer (double edge sword)
Pointers
• address of operator &
! don t confuse with bitwise AND operator
Given
int x; int* p; // p points to an int
p = &x;
Then
*p = 2; and x = 2; produce the same result
Note: p is a pointer, *p is an int
• What happens for p = 2?;
On 32-bit machine, p is 32-bits
Sakai In Class Quiz 2.3
Which Version Correctly Swaps Values?
void swap (int x, int y){
int temp = x;
x = y;
y = temp;
}
main() {
int a = 3;
int b = 4;
swap(a, b);
printf(“a = %d, b= %d\n”,
a, b);
}
void swap (int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
main() {
int a = 3;
int b = 4;
swap(&a, &b);
printf(“a = %d, b= %d\n”,
a, b);
}
A string is an array of characters with \0 at the end
Each element is one byte, ASCII code
\0 is null (ASCII code 0)
char str1[256] is similar to str2 = (char *) malloc(256);