<<

Programming Levels Algorithm level Application Scripting Interpreted Languages Languages Or Compiled High-Level (Java, #) (Perl, Python, VB) Languages System Programming Languages Introduction to C (C and C++) Compilation (, PowerPC, SPARC, MIPS) Low-Level Assembly Languages Machine Langgguage (x86, PowerPC, SPARC, MIPS)

Based on slides © McGraw-Hill ISA level Additional material © 2004/2005 Lewis/Martin Hardware Modified by Diana Palsetia (Application-Specific Integrated Circuits or ASICs)

CIT 593 2

Programming Language: Syntax Semantics

Syntax is the grammar of the language When the computer carries out your instructions (program) „ Running or Executing a program „ Analogous to rules in English Language ¾Missin g a peri od aft er sent en ce Semantics is the meaning of the program ¾Rules using verbs, nouns etc.. „ We learn the semantics after we run or execute the program „ Basically we observe the output

„ Most languages provide syntax check errors After the executing program, the semantics of the program (Interprets/) may or may be correct ¾Syntax error messages may be helpful ¾Often, they are not Semantic errors cause your answers to be wrong ¾You gain experience with error messages after a while „ You may or may not get error messages ¾ E.g. Error Message – Dividing a number by zero

„ If your program is not doing what you want it to do, though it runs, the error is semantic

CIT 593 3 CIT 593 4

1 C Programs are Compiled Compilation Process

C Entire mechanism is usually called the Source and Header Files (text file containing hello. C source code) „ Acts upon C preprocessor directives „ “Source-level” transformations C Preprocessor ¾ Output is still C

Compiler

(text file containing Source Code hello.s assembler source code) Analysis Compiler Symbol Table „ Generates object file Target Code Synthesis ¾ Machine instructions (binaries)

Library hello Linker (a.out) (binary executable file Linker Object Files Containing ) „ Combine object files (including libraries)

into executable image Executable We will use the GNU gcc compiler (v3.0 and higher) Image CIT 593 5 CIT 593 6

Comments in C Basic C Elements Variables Begins with /* and ends with */ „ A data item upon which the performs an operation „ A named space in memory „ Can span multiple lines „ E.g. z, counter

Operators „ Predefined actions performed on data items Begins with // and ends with “end of line” „ E.g. *, +, /, ||, |, && „ Single-line comment Expressions ¾E.g. //This is a comment „ Operators combined with variables/literals to form expressions „ E.g. x * y „ Introduced in C++, later back-ported to C Statements „ Compiling with ansi standards, gives error „ A defined behavior „ Constitutes a unit of work for high-level language „ Ends with a semicolon. E.g. z = x * y;

Why use comments ? Functions „ Help readers understand programs better „ Named group of statements „ Provides modularity to program „ Enforces, DRY principle (Do not Repeat Yourself)

CIT 593 7 CIT 593 8

2 C program structure Variable Properties

int main(){ Identifier: variable name /* code goes here Type: how data is interpreted, and how much space it */ needs return 0; } Every C program must the above format to develop Later we will discuss: application program(s) Scope: is the region of the program in which the variable is „ One of files must contain above structure alive and accessible ¾ main is a special function in C ¾ similar to Java’s main method Storage: how C compiler allocates storage and whether or „ Starting point for every program not the variable loses its value when the block that All C programs start and finish execution in the main contains it has completed execution Note: int main(int argc, char **argv) – main function can also take arguments like in Java CIT 593 9 CIT 593 10

Identifier: Variable Names Identifier Examples Any combination of letters, numbers, and Legal underscore (_) i wordsPerSecond same identifier words_per_ second Case sensitive _green „ "sum" is different than "Sum" aReally_longName_moreThan31chars aReally_longName_moreThan31characters Cannot begin with a number „ Usually, variables beginning with underscore Illegal are used only in special routines 10sdigit ten'sdigit Only first 31 characters are definitely used done? reserved keyword „ Implementations can consider more characters if they like double

CIT 593 11 CIT 593 12

3 Types Additional to C has several basic data types Literal int integer (at least 16 bits, commonly 32 bits) „ Values we write in a conventional form whose value is long integer (at least 32 bits) obvious 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 „ Variable whose values do not change during the „ int is supposed to be "natural" integer size execution of the program ¾ 32 bits for most modern processors „ This done by appending “const” before the type „ So how do I know the size? ¾ Use method called sizeof. E.g. sizeof(int), returns answer in bytes

Signed vs. unsigned: Symbol „ Default is 2’s complement signed integers „ Like constants but is preprocessor „ Use “unsigned” keyword for unsigned numbers

CIT 593 13 CIT 593 14

Literals Constants vs. Symbol Integer #define RADIUS 15.0 123 /* decimal */ -123 symbol 0x123 /* */ int main(){ const dou ble PI = 3. 14159; Floating point double area; constant literal 6.023 double circum; 6.023e23 /* 6.023 x 1023 */ 5E12 /* 5.0 x 1012 */ area = PI * RADIUS * RADIUS; Character circum = 2 * PI * RADIUS; 'c' return 0; '\n' /* newline */ } '\xA' /* ASCII 10 (0xA) */

CIT 593 15 CIT 593 16

4 Symbol is C Preprocessor Directive Expression Symbol start with #define Expression „ Must go before the “main function syntax” „ Any combination of variables, constants, operators, and function calls „ Every expression has a type, derived from the types Example: #define RADIUS 15.0 of its components (according to C typing rules) „ Before compiling, replace all instances of the string “RADIUS“ in the code with the string “15.0" Examples: „ Also known as a macro area = PI * RADIUS * RADIUS; „ Used for values that won't change during execution, but might change if the program is reused. (Must counter >= STOP recompile.) x + sqrt(y) x & z + 3 || 9 - w-- % 6

CIT 593 17 CIT 593 18

Statement Operators Expresses a complete unit of work Three things to know about each operator „ Executed in sequential order (1) Function „ What does it do? Simple statement ends with semicolon (note: “;” is nottiC)t a comment in C) (2) Precedence z = x * y; /* assign product to z */ „ In which order are operators combined? „ Example: y = y + 1; /* update y */ "a * b + c * " is the same as "(a * b) + (c * d)" ; /* null statement */ because multiply (*) has a higher precedence than addition (+)

Compound statement formed with braces (3) Associativity „ Syntactically equivalent to a simple statement „ In which order are operators of the same precedence combined? „ Example: { z = x * y; y = y + 1; } "a - b - c" is the same as "(a - b) - c" because add/sub associate left-to-right

CIT 593 19 CIT 593 20

5 Assignment Operator Assignment Operator (contd..) Changes the value of a variable All expressions evaluate to a value „ Even ones with the assignment operator e.g. y = x = 3

x = x + 4; For assignment, the result is the value assigned „ Usually (but not always) the value of the right-hand 1. Evaluate right-hand side. side ¾Type conversion might make assigned value 2. Set value of left-hand side variable to result. different than computed value e.g. int x = 15.6/3 = 5

Assigggnment associates right to left. y = x = 3; y gets the value 3, because (x = 3) evaluates to the value 3 y = (x = 3);

CIT 593 21 CIT 593 22

Arithmetic Operators Arithmetic Expressions If mixed types, smaller type is "promoted" to larger Symbol Operation Usage Precedence Assoc „ Example: x + 4.3 * multiply x * y 6l-to-r „ if x is int, converted to double and result is double divide 6l-to-r / x / y Integer division -- fraction is dropped % modulo x % y 6l-to-r „ Example: x / 3 + addition x + y 7l-to-r „ if x is int and x=5, result is 1 (not 1.666666...) - subtraction x - y 7l-to-r Storing mixed type expression values „ int x = 45/7.1; All associate left to right „ C compiler will do automatic down grade if storage is small. Java compiler will complain. * /%/ % have higher precedence than + - Example Modulo -- result is remainder „ 2 + 3 * 4 vs. (2 + 3) * 4 „ Example: x % 3 „ if x is int and x=5, result is 2 „ 2 * 4 % 5

CIT 593 23 CIT 593 24

6 Relational Operators Logical Operators

Symbol Operation Usage Precedence Assoc Symbol Operation Usage Precedence Assoc > greater than x > y 9l-to-r ! logical NOT !x 4 r-to-l logical AND 14 l-to-r >= greater than or equal x >= y 9l-to-r && x && y || logical OR x||yx || y 15 l-to-r < less than x < y 9l-to-r <= less than or equal x <= y 9l-to-r Logical Operator is different from bitwise operators == equal x == y 10 l-to-r „ Treats entire variable (or value) as TRUE (non-zero), or != not equal x != y 10 l-to-r FALSE (zero) „ EgE.g. 1 1&&8 && 8 = 1 (True && True = True) Result is non-zero (TRUE) or zero (FALSE)

CIT 593 25 CIT 593 26

Relational and Logical Usage Bitwise Operators

Typically used to construct conditions Symbol Operation Usage Precedence Assoc „ Ultimately conditional will result in TRUE or FALSE ~ bitwise NOT ~x 4 r-to-l „ Note that see has no Boolean type << left shift x << y 8l-to-r ¾ Outcome is zero or non-zero (i.e. int) >> right shift x >> y 8l-to-r Example & bitwise AND x&yx & y 11 l-to-r „ (x > y) && (x < z) ^ bitwise XOR x ^ y 12 l-to-r „ (c == ‘q’) || (c == ‘Q’) | bitwise OR x | y 13 l-to-r Conditions allow change in the „ Can skip certain instructions based on condition Bit-wise vs Logical „ 1 & 8 = 0 (000001 AND 001000 = 000000) if((c == ‘q’) || (c == ‘Q’)){ „ 1 && 8 = 1 (True && True = True) //Quit game } Shift operations „ Operate on values -- neither operand is changed „ If the condition results in TRUE, then statements in the { } will be executed „ x = y << 1 same as x = y + y „ { } is known as block. Basically encloses some number of statements to be executed

CIT 593 27 CIT 593 28

7 …C and the Right Shift Operator (>>) Special Operators: ++ and -- Does right shift sign extend or not? Changes value of variable by 1 before (or after) its „ Answer: Yes and No value is used in an expression Unsigned values: zero extend „ unsigned int x = ~0; Symbol Operation Usage PrecedenceAssoc „ Then, (x >> 10) will have 10 leading zeros ++ postincrement x++ 2 r-to-l Signed values: -- postdecrement x-- 2 r-to-l „ “Right shifting a signed quantity will fill with ++ preincrement ++x 3 r-to-l sign bits (“”) on some machines and with 0-bits (“log ica l s hift”) on others.” - KihKernighan an d -- predecrement --x 3 r-to-l Ritchie „ In practice, it does sign extend Pre: Increment/decrement variable before using its value ¾int x = ~0; /* signed */ Post: Increment/decrement variable after using its value ¾Then, (x >> 10) will still be all 1s

CIT 593 29 CIT 593 30

Using ++ and -- Special Operators: +=, *=, etc. x = 4; Arithmetic and bitwise operators can be combined with assignment operator y = x++; Statement Equivalent assignment Results: x = 5, y = 4 x += y; x = x + y; (because x is incremen te d a fter ass ignmen t) x -= y; x = x - y; x *= y; x = x * y; x = 4; x /= y; x = x / y; x %= y; x = x % y; y = ++x; All have same x &= y; x = x & y; precedence and Results:Results: x = 5, y = 5 x|=y;x |= y; x=x|y;x = x | y; (because x is incremented before assignment) associativity as = x ^= y; x = x ^ y; and associate x <<= y; x = x << y; right-to-left. x >>= y; x = x >> y;

CIT 593 31 CIT 593 32

8 Input and Output Output

Variety of I/O functions in C printf(“Counter value is %d\n", counter); „ Libraries are contain code/programs already written that can be re-used „ This call says to print the variable counter as a decimal integer, „ So we do not have to re-invent the wheel followed by a linefeed (\n) „ Linefeed will make the cursor go onto next line For I/O, must include i.e.#include ¾ Must go below the main function syntax Can print arbitrary expressions, not just variables „ #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 Different formatting options: „ String contains characters to print and formatting directions for variable %d decimal integer %x hexadecimal integer scanf – Scan Formatted ASCII character „ String contains formatting directions for reading input %c %f floating-point number

CIT 593 33 CIT 593 34

Examples Examples of Input

scanf("%d", &startPoint); This code: „ This call says to read a decimal integer and assign it to the variable printf("%d is a prime number.\n", 43); startPoint (& - specifies the address of the operand….more on this printf("43 plus 59 in decimal is %d.\n", when we do pointers) 4393+59); printf("43 plus 59 in hex is %x.\n", Same formatting characters are available for user input 43+59); printf("43 plus 59 as a character is scanf("%c", &nextChar); %c.\n", 43+59); „ reads a single character and stores it in nextChar scanf("%f", &radius); produces this output: „ reads a floating point number and stores it in radius 43 is a prime number. scanf("%d %d", &length, &width); 43 plus 59 in decimal is 102. „ reads two decimal integers (separated by whitespace), stores the first one in length and the second in width 43 plus 59 in hex is 66. „ Scanf has some limitations….more on it later 43 plus 59 as a character is f.

CIT 593 35 CIT 593 36

9