03 - Lecture 3| Lexical Elements, Operators, and the C...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lecture 3| Lexical Elements, Operators, and the C System Characters and Lexical Elements Keywords Identi ers Constants String Constants Operators and Punctuators Precedence and Associativity of Operators Increment and Decrement Operators Assignment Operators Circle Area Comments Compilation and Linking The Preprocessor The Standard Library The C System Readings Exercises CSC 1500 { Lecture 3 1 Overview C, as a language, has a set of rules for putting together words and punctuations to make correct programs. These rules are the syntax of the language. Analogus to English grammar rules. For a program to be compiled successfully, it must be syntactically correct . C compilers will fail to compile a syntactically incorrect program, no matter how trivial the error is. CSC 1500 { Lecture 3 2 Characters and Lexical Elements /* Read in two integers and print their sum. */ #include <stdio.h> int main(void) { int a, b, sum printf("Input two integers: ") scanf("%d%d", &a, &b) sum = a + b printf("%d + %d = %d\n", a, b, sum) return 0 } The compiler views a program as a series of tokens . In ANSI C, there are six kinds of tokens: Token Type keyword identi er constant string constant operator punctuator Example int, return, void main, a, b, sum, printf, scanf 0 "Input two integers: (), =, +, & , " fg CSC 1500 { Lecture 3 3 Keywords Keywords auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Keywords have a strict meaning. Cannot be rede ned or used in other ways, i.e. reserved . Compared to other major high level programming languages, C has a small number of keywords | 32 only. CSC 1500 { Lecture 3 4 Identifiers Identi ers are used to give unique names to various objects in a program, such as a variable. An identi er is a token that is composed of a sequence of letters, digits, and the underscore ( ). The rst letter of an identi er must be a letter or an underscore. Example identi ers: One2Free, inches, radius, id, student name, main, printf Invalid identi ers: 12Free, #num, 101 south, -plus Lower- and upper-case letters are treated as distinct | my name is di erent from My name. Choose identi ers that have mnemonic signi cance, for example, tax = price * tax_rate Compare to a=b*c main is a special identi er to signify where program execution should start. CSC 1500 { Lecture 3 5 Exercise Which of the following are not valid identi ers and why? 3id 1_i_am o_no_o_no one_i_aren't 00_go me_to-2 start*it xYshouldI __yes int CSC 1500 { Lecture 3 6 Constants Decimal integer constants , for example, 0 17 Floating point number constants , for example, 1.0 3.14 Character constants , for example, 'a' 'b' '\n' '\t' String constants (next page) Enumeration constants (discussed later) CSC 1500 { Lecture 3 7 String Constants A string constant is a sequence of characters enclosed in a pair of double quote ("), for example, "C is easy to learn." String constants are di erent from character constants | "a" is di erent from 'a'. 6= a=b+c The content of the former is just a sequence of characters while the latter is a C statement. "a = b + c " Example, #include <stdio.h> int main(void) { printf printf printf printf printf printf return } ("a string with \"double quotes\".") ("\n") ("a single backslash \\ is in this string.") ("\n") ("a = b + c ") ("\n") 0 a string with "double quotes". a single backslash \ is in this string. a=b+c CSC 1500 { Lecture 3 8 Operators and Punctuators Arithmetic operators , for example, + * / % Operators which take two operands (Binary operators ), for example, a+b 17 * 3 x=y Operators which take only one operand (Unary operators ), for example, x++ &sum Operators can be used to delineate identi ers, for example, sum=a+b But we typically put white space around binary operators to improve readability . sum = a + b Examples of punctuators are | parentheses, braces, commas, and semicolons. CSC 1500 { Lecture 3 9 Precedence and Associativity of Operators Operators have precedence and associativity that determine precisely how expressions are evaluated. 1+2*3 The operator * has higher precedence than +, causing the multiplication to be performed rst. (1 + 2) * 3 Parenthesis can be used to change the order in which operations are performed. is equivalent to (((1 + 2) - 3) + 4) - 5. Because + and - have the same precedence, the expression is evaluated using the associativity rule \left to right." 1+2-3+4-5 Precedence Highest Lowest () ++ post x] ;; post x] + unary] ; unary] ++ pre x] ;; pre x] multiplication] / division] % remainder] + addition] ; subtraction] = += ; = = /= etc. Operator precedence and associativity Operator Associativity left to right right to left left to right left to right right to left Operators on the same line in the above table have equal precedence with respect to each other. -a*b-c is equivalent to ((- a) * b) - c CSC 1500 { Lecture 3 10 Increment and Decrement Operators Short form: age = age + 1 age++ Short form: age = age - 1 age-The increment operator ++. The decrement operator --. Both ++ and -- can be applied to variables, but not to constants or ordinary expressions, for example, i++ 777++ /* valid */ /* invalid */ Both can occur in either pre x or post x position, with di erent results. { Each of the expression ++i and i++ has a value. { The pre x expression ++i causes the stored value of i to be incremented (by one) rst, then the expression evaluates to the newly stored value of i. { The post x expression i++ evaluates to the current value of i rst, then the stored value of i is incremented (by one). Consider the example: int variable, prefix_result, postfix_result variable = 10 prefix_result = ++variable printf("%d %d\n", prefix_result, variable) variable = 10 postfix_result = variable++ printf("%d %d\n", postfix_result, variable) /* 11 11 is printed */ /* 10 11 is printed */ The -- operator is similar to ++, except that the associated variable is decremented (by one). CSC 1500 { Lecture 3 11 Exercise Declarations and Initializations int a=1, b=2, c=3, d=4 a 1 2 b 3 c 4 d Expression a*b/c a*b%c+1 ++ a * b - c -7 * b -- * ++ d Equivalent Expression Value (a * b) / c 0 CSC 1500 { Lecture 3 12 Assignment Operators variable = right_side_expression Low precedence, right-to-left associativity The value of the right side expression is assigned to variable. AND the value becomes the value of this assignment expression as a whole, for example, #include <stdio.h> int main(void) { int a=3, b=4, sum printf ("Value = %d\n", sum=a+b) printf ("Sum = %d\n", sum) return 0 } Value = 7 Sum = 7 Multiple assignment , for example, a=b=c=0 a = (b = (c = 0) ) CSC 1500 { Lecture 3 13 Assignment Operators k=k+2 (con't) += 2 is equivalent to k . The semantics of variable = variable op (expression) is equivalent to variable op= expression Assignment operators = += ;= = /= %= etc. Note carefully j *= k + 3 is equivalent to j = j * (k + 3) rather than j=j*k+3 CSC 1500 { Lecture 3 14 Circle Area #include <stdio.h> #define PI 3.14 int main(void) { float radius=1.5 printf ("Radius=%.1f\n", radius) printf ("Area =%.2f\n", radius*radius*PI) return 0 } Radius=1.5 Area =7.07 The preprocessor automatically changes all occurrences of the identi er PI to 3.14. (Textual Replacement) Thus, printf ("Area =%.2f\n", radius*radius*PI) becomes printf ("Area PI =%.2f\n", radius*radius*3.14) is called a Symbolic Constant. CSC 1500 { Lecture 3 15 Comments /* a comment */ /*** another comment ***/ /*****/ /* * A comment can be written in this fashion * to set it off from the surrounding code. */ /***************************** * If you wish, you can * * put comments in a box. * *****************************/ /* /* This is not allowed */ */ The compiler ignores the comments. Comments are used by programmers as a documentation aid. The aim of documentation is to explain clearly how the program works and how it is to be used. Comments should be written simultaneously when you write the program. CSC 1500 { Lecture 3 16 Compilation and Linking The C system consists of { the C language { the preprocessor { the compiler { the library { and other tools such as debuggers CSC 1500 { Lecture 3 17 The Preprocessor Lines that begin with a # are called preprocessing directives , for example, #include <stdio.h> #define PI 3.14 #include < lename > instructs the preprocessor to replace the line with a copy of the contents of the named le in system default directories. #include " lename " similar to < lename > except that the preprocessor searches the current directory rst before trying the system default directories. Since #include directives commonly occur at the beginning of the program, the included les are called header les and their lename extension is usually .h Header les normally contain variable declarations, function prototypes and other preprocessing directives. The included header le can contain other preprocessing directives that will be expanded by the preprocessor in turn. *Roughly speaking, a function prototype tells the compiler the types of arguments passed to the function and the type of the value returned by the function. The compiler needs function prototypes to do its work correctly. An example, int printf (const char *format, ...) CSC 1500 { Lecture 3 18 The Standard Library The standard library contains many prede ned functions that add considerable power to the C system. Examples are printf(), scanf(), rand(), ... Even though the C system provides the object code ( machine instructions) of the functions, it's the responsibility of programmers to provide their function prototypes. Therefore, #include are very common in C programs. #include <stdio.h> #define PI 3.14 int main(void) { float radius=1.5 printf ("Radius=%.1f\n", radius) printf ("Area =%.2f\n", radius*radius*PI) return 0 } Many of the functions are used frequently while others are used more occasionally. Most C programmers learn standard library functions on a need-to-know basis. Therefore, a good reference manual , either hardcopy or online, is very important to every C programmer. CSC 1500 { Lecture 3 19 The C System stdlib header files preprocessing Expanded source code compile circle.c circle.obj + printf object = circle.exe Linking CSC 1500 { Lecture 3 20 Readings Chapter 2, Sections 2.1 { 2.10 Chapter 2, Sections 2.12 { 2.14 Exercises Chapter 2, Exercises 1, 11, 12, 13, 15 2 End of Lecture 3 CSC 1500 { Lecture 3 21 ...
View Full Document

This note was uploaded on 05/23/2010 for the course COMPUTER S CSC1500 taught by Professor Fung during the Spring '10 term at CUHK.

Ask a homework question - tutors are online