Programming Levels Application Languages (Java, C#)
High-Level Languages
Algorithm level
Scripting Interpreted Languages Or Compiled (Perl, Python, VB)
System Programming Languages (C and C++)
Introduction to C
Compilation
Assembly Language (x86, PowerPC, SPARC, MIPS)
Low-Level Languages
Machine Language g g (x86, PowerPC, SPARC, MIPS)
Based on slides © McGraw-Hill Additional material © 2004/2005 Lewis/Martin Modified by Diana Palsetia
Hardware (Application-Specific Integrated Circuits or ASICs)
Assembly
ISA level
2
CIT 593
Programming Language Semantics
Programming Language: Syntax
When the computer carries out your instructions (program)
Syntax is the grammar of the language
Analogous to rules in English Language
Semantics is the meaning of the program
¾ Missing ss g a pe period od a after e se sentence e ce ¾ Rules using verbs, nouns etc..
Running or Executing a program
Most languages provide syntax check errors (Interprets/Compilers)
We learn the semantics after we run or execute the program Basically we observe the output
After the executing program, the semantics of the program may or may be correct
¾ Syntax error messages may be helpful ¾ Often, Often they are not ¾ You gain experience with error messages after a while
Semantic errors cause your answers to be wrong
You may or may not get error messages
If your program is not doing what you want it to do, though it runs, the error is semantic
¾
CIT 593
3
CIT 593
E.g. Error Message – Dividing a number by zero
4
1
Compilation Process
C Programs are Compiled
Entire mechanism is usually called the compiler hello.c
(text file containing C source code)
C Source and Header Files
Preprocessor
Acts upon C preprocessor directives “Source-level” transformations
C Preprocessor
¾ Output is still C
hello.s
Compiler
(text file containing assembler source code)
Source Code Analysis
Compiler
Symbol Table
Generates object file
Target Code Synthesis
¾ Machine instructions (binaries)
hello (a.out)
Library Object Files
Linker
(binary executable file Containing machine code )
Combine object files (including libraries) into executable image
We will use the GNU gcc compiler (v3.0 and higher) 5
CIT 593
Executable Image
6
CIT 593
Comments in C
Basic C Elements Variables
Begins with /* and ends with */
Linker
Can span multiple lines
A data item upon which the programmer performs an operation A named space in memory E.g. z, counter
Operators p
Begins with // and ends with “end of line”
Single-line comment
Expressions
¾ E.g. //This is a comment
Introduced in C++, later back-ported to C Compiling with ansi standards, gives error
Why use comments ?
A defined behavior Constitutes a unit of work for high-level language Ends with a semicolon. E.g. z = x * y;
Functions
Help readers understand programs better
CIT 593
Operators combined with variables/literals to form expressions E.g. x * y
Statements
Predefined actions performed on data items E.g. *, +, /, ||, |, &&
7
CIT 593
Named group of statements Provides modularity to program Enforces, DRY principle (Do not Repeat Yourself) 8
2
C program structure
Variable Properties Identifier: variable name
int main(){ /* code goes here */ return 0; }
Type: how data is interpreted, and how much space it needs Later we will discuss: Scope: is the region of the program in which the variable is alive and accessible
Every C program must the above format to develop application program(s)
One of files must contain above structure ¾ main is a special function in C ¾ similar to Java’s main method
Storage: how C compiler allocates storage and whether or not the variable loses its value when the block that contains it has completed execution
Starting point for every program
All C programs start and finish execution in the main Note: int main(int argc, char **argv) – main function can also take arguments like in Java 9
CIT 593
10
CIT 593
Identifier: Variable Names
Identifier Examples Legal
Any combination of letters, numbers, and underscore (_)
i wordsPerSecond same identifier words_p per_second _green aReally_longName_moreThan31chars aReally_longName_moreThan31characters
Case sensitive
"sum" is different than "Sum"
Cannot begin with a number
Illegal
Usually, variables beginning with underscore are used only in special library routines
10sdigit ten'sdigit done? double
Only first 31 characters are definitely used
CIT 593
Implementations can consider more characters if they like
11
CIT 593
reserved keyword
12
3
Types
Additional to Data Type
C has several basic data types
Literal
int integer (at least 16 bits, commonly 32 bits) long integer (at least 32 bits) float floating point (at least 32 bits) double floating point (commonly 64 bits) char character (at least 8 bits)
Constant
Exact size can vary, depending on processor
int is supposed to be "natural" integer size
So how do I know the size?
Values we write in a conventional form whose value is obvious
¾ 32 bits for most modern processors
Variable whose values do not change during the execution of the program This done by appending “const” before the type
¾ Use method called sizeof. E.g. sizeof(int), returns answer in bytes
Symbol
Signed vs. unsigned:
Default is 2’s complement signed integers Use “unsigned” keyword for unsigned numbers
13
CIT 593
Constants vs. Symbol
Integer
#define RADIUS 15.0
123 /* decimal */ -123 0x123 /* hexadecimal */
symbol
int main(){ constt d double bl PI = 3 3.14159; 14159 double area; constant double circum;
Floating point /* 6.023 x 1023 */ /* 5.0 x 1012 */
literal
area = PI * RADIUS * RADIUS; circum = 2 * PI * RADIUS; return 0;
Character 'c' '\n' /* newline */ '\xA' /* ASCII 10 (0xA) */ CIT 593
14
CIT 593
Literals
6.023 6.023e23 5E12
Like constants but is preprocessor directive
} 15
CIT 593
16
4
Symbol is C Preprocessor Directive
Expression Expression
Symbol start with #define
Must go before the “main function syntax”
Example: #define RADIUS 15.0
Before compiling, replace all instances of the string “RADIUS“ in the code with the string “15.0" Also known as a macro Used for values that won't change during execution, but might change if the program is reused reused. (Must recompile.)
Examples: area = PI * RADIUS * RADIUS; counter >= STOP x + sqrt(y) x & z + 3 || 9 - w-- % 6 17
CIT 593
Any combination of variables, constants, operators, and function calls Every expression has a type type, derived from the types of its components (according to C typing rules)
Statement
Operators
Expresses a complete unit of work
Three things to know about each operator (1) Function
Executed in sequential order
Simple statement ends with semicolon (note: “;” is nott a commentt in i C) z = x * y; /* assign product to z */ y = y + 1; /* update y */ ; /* null statement */ Compound statement formed with braces
What does it do?
(2) Precedence
In which order are operators combined? Example: "a * b + c * d" is the same as "(a * b) + (c * d)" because multiply (*) has a higher precedence than addition (+)
(3) Associativity
Syntactically equivalent to a simple statement
{ z = x * y; y = y + 1; }
CIT 593
18
CIT 593
19
In which order are operators of the same precedence combined? Example: "a - b - c" is the same as "(a - b) - c" because add/sub associate left-to-right
CIT 593
20
5
Assignment Operator
Assignment Operator (contd..)
Changes the value of a variable
All expressions evaluate to a value
x = x + 4;
Even ones with the assignment operator e.g. y = x = 3
For assignment, the result is the value assigned
1. Evaluate right-hand side.
Usually (but not always) the value of the right-hand side ¾ Type conversion might make assigned value different than computed value e.g. int x = 15.6/3 = 5
2. Set value of left-hand side variable to result.
Assignment g associates right g to left. y = x = 3; y gets the value 3, because (x = 3) evaluates to the value 3
y = (x = 3); 21
CIT 593
Arithmetic Operators Symbol * / % + -
Operation multiply divide modulo addition subtraction
Usage x * y x / y x % y x + y x - y
Arithmetic Expressions
Precedence Assoc 6 l-to-r 6
l-to-r
6
l-to-r
7
l-to-r
7
l-to-r
If mixed types, smaller type is "promoted" to larger
Example: x / 3 if x is int and x=5, result is 1 (not 1.666666...)
Storing mixed type expression values
* / % have higher precedence than + -
Example
Example: x + 4.3 if x is int, converted to double and result is double
Integer g division -- fraction is dropped pp
All associate left to right
int x = 45/7.1; C compiler will do automatic down grade if storage is small. Java compiler will complain.
Modulo -- result is remainder
2
+ 3 * 4 vs. (2 + 3) * 4 2* 4% 5 CIT 593
22
CIT 593
23
CIT 593
Example: x % 3 if x is int and x=5, result is 2
24
6
Relational Operators Symbol Operation > greater than >= greater than or equal < less than y 9 x >= y 9 x < y 9 x & ^ |
Ultimately conditional will result in TRUE or FALSE Note that see has no Boolean type ¾ Outcome is zero or non-zero (i.e. int)
Example (x > y) && (x < z) (c == ‘q’) || (c == ‘Q’)
Conditions allow change in the control flow
CIT 593
Usage ~x x > y x & y x ^ y x | y
Precedence 4 8 8 11 12 13
Assoc r-to-l l-to-r l-to-r l-to-r l-to-r l-to-r
Bit-wise vs Logical
Can skip certain instructions based on condition if((c == ‘q’) || (c == ‘Q’)){ //Quit game }
Operation bitwise NOT left shift right shift bitwise AND bitwise XOR bitwise OR
1 & 8 = 0 (000001 AND 001000 = 000000) 1 && 8 = 1 (True && True = True)
Shift operations
If the condition results in TRUE, then statements in the { } will be executed { } is known as block. Basically encloses some number of statements to be executed 27
CIT 593
Operate on values -- neither operand is changed x = y >)
Special Operators: ++ and -Changes value of variable by 1 before (or after) its value is used in an expression
Does right shift sign extend or not?
Answer: Yes and No
Unsigned g values: zero extend
Symbol Operation ++ postincrement -- postdecrement ++ preincrement -- predecrement
unsigned int x = ~0; Then, (x >> 10) will have 10 leading zeros
Signed values:
“Right shifting a signed quantity will fill with sign bits (“arithmetic shift”) on some machines and with ith 0 0-bits bit (“l (“logical i l shift”) hift”) on others.” th ” - Kernighan K i h and d Ritchie In practice, it does sign extend
29
2
r-to-l
2
r-to-l
3
r-to-l
3
rr-to-l to l
30
CIT 593
Using ++ and --
Special Operators: +=, *=, etc. Arithmetic and bitwise operators can be combined with assignment operator Statement Equivalent assignment
x = 4; y = x++; Results: x = 5, y = 4 (b (because x iis iincremented t d after ft assignment) i t)
x x x x x x x x x x
x = 4; y = ++x; Results: x = 5, y = 5 (because x is incremented before assignment)
CIT 593
PrecedenceAssoc
Pre: Increment/decrement variable before using its value Post: Increment/decrement variable after using its value
¾ int x = ~0; /* signed */ ¾ Then, (x >> 10) will still be all 1s CIT 593
Usage x++ x-++x --x x
31
+= y; -= y; *= y; /= y; %= y; &= y; |= y; ^= y; = y;
CIT 593
x x x x x x x x x x
= = = = = = = = = =
x x x x x x x x x x
+ y; - y; * y; / y; % y; & y; | y; ^ y; > y;
All have same precedence and associativity as = and associate right-to-left.
32
8
Input and Output
Output printf(“Counter value is %d\n", counter);
Variety of I/O functions in C Standard Library
Libraries are contain code/programs already written that can be re-used So we do not have to re-invent the wheel
This call says to print the variable counter as a decimal integer, followed by a linefeed (\n) Linefeed will make the cursor go onto next line
For I/O, must include stdio.h i.e.#include
Can print arbitrary expressions, not just variables
¾ Must go below the main function syntax
#include is a C processor Directive
printf("%d\n", startPoint - counter);
¾ Before compiling, copy contents of stdio.h into source code ¾ .h files typically contain descriptions of functions and structs
Print multiple expressions with a single statement printf("%d %d\n", counter, startPoint - counter);
printf – Print formatted
Performs output to standard output device String contains characters to print and formatting directions for variable
Different formatting options: %d decimal integer %x hexadecimal integer %c ASCII character %f floating-point number
scanf – Scan Formatted
String contains formatting directions for reading input
33
CIT 593
34
CIT 593
Examples
Examples of Input scanf("%d", &startPoint);
This code:
printf("%d is a printf("43 plus 43+59); 3 9 printf("43 plus 43+59); printf("43 plus %c.\n", 43+59);
prime number.\n", 43); 59 in decimal is %d.\n", 59 in hex is %x.\n",
This call says to read a decimal integer and assign it to the variable startPoint (& - specifies the address of the operand….more on this when we do pointers)
Same formatting characters are available for user input scanf("%c", &nextChar);
59 as a character is
reads a single character and stores it in nextChar
scanf("%f", &radius);
produces this output: 43 43 43 43 CIT 593
is a plus plus plus
prime 59 in 59 in 59 as
reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
number. decimal is 102. hex is 66. a character is f.
35
reads two decimal integers (separated by whitespace), stores the first one in length and the second in width Scanf has some limitations….more on it later
CIT 593
36
9