Syntax of C Programming Language #Lesson 2 Sen Zhang.

49
Syntax of C Syntax of C Programming Language Programming Language #Lesson 2 #Lesson 2 Sen Zhang Sen Zhang

Transcript of Syntax of C Programming Language #Lesson 2 Sen Zhang.

Page 1: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Syntax of C Programming Syntax of C Programming LanguageLanguage

#Lesson 2#Lesson 2

Sen ZhangSen Zhang

Page 2: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Topics CoveredTopics Covered

Lexical elementsLexical elements GrammarGrammar Case sensitiveCase sensitive Reserved WordsReserved Words IdentifiersIdentifiers Data TypesData Types VariablesVariables ConstantsConstants Operations on dataOperations on data

Page 3: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Lexical elementsLexical elements

If you look at any program, you will see that a If you look at any program, you will see that a program simply consists of reserved words, program simply consists of reserved words, identifiers, constants (literals or constant identifiers, constants (literals or constant symbols), operators glue them together and symbols), operators glue them together and punctuators to delimit them.punctuators to delimit them.

The above tokens (separable units) are put The above tokens (separable units) are put together under certain rules (both syntactic and together under certain rules (both syntactic and logical).logical).

Page 4: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Natural LanguageNatural Language

GrammarGrammar Syntax (sentence, paragraph, article.)Syntax (sentence, paragraph, article.) Lexical (Vocabulary, verb, noun, etc.)Lexical (Vocabulary, verb, noun, etc.)

Reserved VocabularyReserved Vocabulary DataData

Constant, symbol Constant, symbol New VocabularyNew Vocabulary

New dataNew data New functionNew function

Page 5: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Syntax and SemanticsSyntax and Semantics

Syntax is the structure of a language:Syntax is the structure of a language: ““What programs can I write?”What programs can I write?” ““Will the compiler accept this program?”Will the compiler accept this program?”

Semantics is the meaning of a language:Semantics is the meaning of a language: ““How do programs work?”How do programs work?” ““What will this program do?”What will this program do?”

Page 6: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Syntax TreesSyntax Trees

A grammar says how a syntax tree can be A grammar says how a syntax tree can be built:built:

sentencesentence clauseclause noun-phrasenoun-phrase noun verb prep article nounnoun verb prep article noun ““Time flies like an arrow.”Time flies like an arrow.”

Page 7: Syntax of C Programming Language #Lesson 2 Sen Zhang.

A comparison A comparison

A document (an instruction manual) -> programA document (an instruction manual) -> program A paragraph -> a block or a functionA paragraph -> a block or a function A sentence or subclause -> a statementA sentence or subclause -> a statement A phrase -> an expressionA phrase -> an expression A word or term identifier -> a constant or a variable A word or term identifier -> a constant or a variable

namename

Page 8: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Lexical ElementsLexical Elements

A lexical element refers to a character or A lexical element refers to a character or groupings of characters that may legally groupings of characters that may legally appear in a source file. appear in a source file.

Page 9: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Source program character setSource program character set The following lists the basic source character sets that are available at both The following lists the basic source character sets that are available at both

compile time and run time: compile time and run time: The uppercase and lowercase letters of the English alphabet: The uppercase and lowercase letters of the English alphabet:

a b c d e f g h i j k l m n o p q r s t u v w x y za b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y ZA B C D E F G H I J K L M N O P Q R S T U V W X Y Z

The decimal digits: 0 1 2 3 4 5 6 7 8 9The decimal digits: 0 1 2 3 4 5 6 7 8 9 The following graphic characters: The following graphic characters: ! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] _ { } ^ |~! " # % & ' ( ) * + , - . / : ; < = > ? [ \ ] _ { } ^ |~ The space character The space character The control characters representing new-line, horizontal tab, vertical tab, form The control characters representing new-line, horizontal tab, vertical tab, form

feed, end of string (NULL character), alert, backspace, and carriage return.feed, end of string (NULL character), alert, backspace, and carriage return.

ASCII codesASCII codes

Page 10: Syntax of C Programming Language #Lesson 2 Sen Zhang.

TokensTokens

Source code is treated during preprocessing and Source code is treated during preprocessing and compilation as a sequence of tokens. compilation as a sequence of tokens.

A token is the smallest independent unit of meaning in a A token is the smallest independent unit of meaning in a program, as defined by the compiler. program, as defined by the compiler.

There are five different types of tokens: There are five different types of tokens: Keywords Keywords Identifiers Identifiers Literals Literals Punctuator Punctuator operatorsoperators

Page 11: Syntax of C Programming Language #Lesson 2 Sen Zhang.

KeywordsKeywords

Keywords are words reserved by the language for special use. Keywords are words reserved by the language for special use. Although you can use them for preprocessor macro names, Although you can use them for preprocessor macro names,

it is considered poor programming style. (At csci109 and it is considered poor programming style. (At csci109 and csci116 level, you just do not redefine keywords at csci116 level, you just do not redefine keywords at anywhere. ) anywhere. )

Also called reserved words, cannot be used as identifiers.Also called reserved words, cannot be used as identifiers. Since the language is case sensitive, only the exact spelling of Since the language is case sensitive, only the exact spelling of

keywords is reserved. For example, auto is reserved but keywords is reserved. For example, auto is reserved but AUTO is not. AUTO is not.

Page 12: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Difference between a keyword Difference between a keyword and an identifier?and an identifier?

Keywords are reserved words like(int, float) which Keywords are reserved words like(int, float) which have special meanings for compilers. have special meanings for compilers.

Identifiers are given by programmers to label any Identifiers are given by programmers to label any variable or any name used to identify an variable, variable or any name used to identify an variable, function, constant value, object or entity.function, constant value, object or entity.

Hence keywords cannot be used as an identifier Hence keywords cannot be used as an identifier

Page 13: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Adjacent identifiers, keywords, and literals Adjacent identifiers, keywords, and literals must be separated with operators or must be separated with operators or punctuators or sometimes space.punctuators or sometimes space.

Other tokens should be separated by white Other tokens should be separated by white space to make the source code more readable. space to make the source code more readable. White space includes blanks, horizontal and White space includes blanks, horizontal and vertical tabs, new lines, form feeds, and vertical tabs, new lines, form feeds, and comments.comments.

Page 14: Syntax of C Programming Language #Lesson 2 Sen Zhang.

A punctuator is a token that has syntactic and A punctuator is a token that has syntactic and semantic meaning to the compiler, but the semantic meaning to the compiler, but the exact significance depends on the context. A exact significance depends on the context. A punctuator can also be a token that is used in punctuator can also be a token that is used in the syntax of the preprocessor.the syntax of the preprocessor.

Page 15: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Reserved WordsReserved Words The reserved words are predefined identifiers or names The reserved words are predefined identifiers or names

used internally by C compiler. used internally by C compiler. They are always written in lower case.They are always written in lower case. You shouldn't use them for any other purpose in a C You shouldn't use them for any other purpose in a C

program.program. There are 32 words defined as keywords in C.There are 32 words defined as keywords in C.

Page 16: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Reserved word cont’Reserved word cont’

auto double int struct break else long switch case enum auto double int struct break else long switch case enum register typedef char extern return union const float short register typedef char extern return union const float short unsigned continue for signed void default goto sizeof unsigned continue for signed void default goto sizeof

volatile do if static whilevolatile do if static while Although main is not in the reserved words list, it Although main is not in the reserved words list, it

should not be taken as a user-defined identifier for should not be taken as a user-defined identifier for your variable or other function names except for the your variable or other function names except for the main function itself to avoid confusion. This is main function itself to avoid confusion. This is because main is the entry point for an independent because main is the entry point for an independent executable C program.executable C program.

Page 17: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Case sensitiveCase sensitive

Int is not a keyword, int is.Int is not a keyword, int is. Case matters.Case matters.

Page 18: Syntax of C Programming Language #Lesson 2 Sen Zhang.

WHAT IS AN IDENTIFIER?WHAT IS AN IDENTIFIER?

Before you can do anything in any language, Before you can do anything in any language, you must know how to name an identifier you must know how to name an identifier (Noun in natural language, if you tend to think (Noun in natural language, if you tend to think some reserved words verbs. Although this some reserved words verbs. Although this comparison is not always true.) comparison is not always true.)

An identifier is used for any variable, function, An identifier is used for any variable, function, constant data definition, etc. constant data definition, etc.

Page 19: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Identifier Naming ConventionsIdentifier Naming Conventions

Identifiers (variable names are kinds of identifiers) Identifiers (variable names are kinds of identifiers) must follow these rules:must follow these rules: consist of a sequence of letters, digits, and underscore.consist of a sequence of letters, digits, and underscore. cannot start with a digit.cannot start with a digit. can be of any length, only the first 31 characters are can be of any length, only the first 31 characters are

significant.significant. are case sensitive.are case sensitive. cannot be the same as keywords (reserved words)cannot be the same as keywords (reserved words)

Page 20: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Examples of legal Identifier NamesExamples of legal Identifier Names

Legal variable namesLegal variable namesClassSizeClassSize

_previous_value_previous_value

PercentPercent

PerCentPerCent

PERCENTPERCENT

Kdff123Kdff123

kkkkkkkkkk

Page 21: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Examples of illegal identifier namesExamples of illegal identifier names

identifiersidentifiers reasonsreasons

savings#accountsavings#account Contains the illegal character #Contains the illegal character #

DoubleDouble Is a C keywordIs a C keyword

rad iusrad ius Space is illegalSpace is illegal

Tax-RateTax-Rate - is illegal- is illegal

unionunion A reserved wordA reserved word

9winter9winter First character is a digitFirst character is a digit

Page 22: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Two rules must be kept in mind when naming identifiers. Two rules must be kept in mind when naming identifiers. C is case-sensitive. The case of alphabetic characters is C is case-sensitive. The case of alphabetic characters is

significant. The names percent, PERCENT, and Percent significant. The names percent, PERCENT, and Percent would be considered three different variables.would be considered three different variables.

According to the ANSI-C standard, at least 31 According to the ANSI-C standard, at least 31 significant characters can be used and will be considered significant characters can be used and will be considered significant by a conforming ANSI-C compiler. If more significant by a conforming ANSI-C compiler. If more than 31 are used, all characters beyond the 31st may be than 31 are used, all characters beyond the 31st may be ignored by any given compiler.ignored by any given compiler.

Page 23: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Data typesData types

''data typesdata types' are used to define a variable before ' are used to define a variable before its use. its use.

The definition of a variable will assign storage The definition of a variable will assign storage for the variable and define the type of data that for the variable and define the type of data that will be held in the location.will be held in the location.

Page 24: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Major Data Types in CMajor Data Types in C Scalar TypesScalar Types

integerinteger floatfloat doubledouble charactercharacter

VoidVoid Aggregate TypesAggregate Types

ArraysArrays stringsstrings

structuresstructures

Page 25: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Basic data typesBasic data types

void associated with no data type void associated with no data type int integerint integer float floating-point numberfloat floating-point number double double precision floating-point numberdouble double precision floating-point number char characterchar character

Page 26: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Data type is defined by two propertiesData type is defined by two properties A set of values, domain, which represents the set A set of values, domain, which represents the set

of values that are valid elements of that type.of values that are valid elements of that type. For example, the domain of the integer type includes all For example, the domain of the integer type includes all

integers. integers. A set of operations, which defines the operations A set of operations, which defines the operations

which are meaningful in that data type domain. which are meaningful in that data type domain. For example you can multiple two integers, but you For example you can multiple two integers, but you

cannot multiple two characters.cannot multiple two characters.

Page 27: Syntax of C Programming Language #Lesson 2 Sen Zhang.

The Integer TypeThe Integer Type

intint is a data type specifier used to declare integer is a data type specifier used to declare integer value variables.value variables.

Includes: Includes: intint, , shortshort, and , and longlong The The intint type usually occupies a word in memory type usually occupies a word in memory If a word has N bits, the range of integers is between If a word has N bits, the range of integers is between

-2-2N-1 N-1 and 2and 2N-1 N-1 - 1- 1 shortshort <= <= intint <= <= longlong Most of time, Most of time, intint should be used! should be used! Operator can be used are +, -, *, / and %.Operator can be used are +, -, *, / and %.

Page 28: Syntax of C Programming Language #Lesson 2 Sen Zhang.

The Floating Point TypeThe Floating Point Type

A data type for declaring floating point variables, A data type for declaring floating point variables, i.e. for numbers that have a fractional part.i.e. for numbers that have a fractional part.

may be expressed with or without the e-notation:may be expressed with or without the e-notation:

123.456123.456 1.23456e+021.23456e+02 there are: there are: floatfloat, , doubledouble, and , and long doublelong double.. By default, floating point constants will be By default, floating point constants will be

considered double.considered double.

Page 29: Syntax of C Programming Language #Lesson 2 Sen Zhang.

A floating point constant must end with an f A floating point constant must end with an f or F: 123.45for F: 123.45f

A long double constant must end with an l A long double constant must end with an l or L: 123.45Lor L: 123.45L

Declaration of floating point type:Declaration of floating point type:float x;float x;

double y;double y;

long double z;long double z; The arithmetic operator used with the float The arithmetic operator used with the float

type are: + - * /type are: + - * /

Page 30: Syntax of C Programming Language #Lesson 2 Sen Zhang.

The relational operator used with the float The relational operator used with the float type are < <= > >= != ==type are < <= > >= != ==

The logical operator used with the float type The logical operator used with the float type are: ! && ||are: ! && ||

Page 31: Syntax of C Programming Language #Lesson 2 Sen Zhang.

The Character TypeThe Character Type

charchar is a data type used to declare character is a data type used to declare character variables.variables.

The ASCII character set consists of 128 The ASCII character set consists of 128 characters.characters.

Each element of the character set is associated Each element of the character set is associated with an integer (0 - 127)with an integer (0 - 127)

Use a pair of single quotes to delimit a Use a pair of single quotes to delimit a character.character.

Page 32: Syntax of C Programming Language #Lesson 2 Sen Zhang.

variablesvariables

A A variablevariable is a name assigned to a data storage is a name assigned to a data storage location. Your program uses variables to store location. Your program uses variables to store various kinds of data during program various kinds of data during program execution. In C, a variable must be defined execution. In C, a variable must be defined before it can be used. before it can be used.

By using a variable's name in your program, By using a variable's name in your program, you are, in effect, referring to the data stored you are, in effect, referring to the data stored there. there.

Variables names are a kind of identifiers.Variables names are a kind of identifiers.

Page 33: Syntax of C Programming Language #Lesson 2 Sen Zhang.

VariablesVariables

A variable is a placeholder for a value and has A variable is a placeholder for a value and has 5 attributes: 5 attributes: name or identifier, name or identifier, address, address, Type (size and operations) Type (size and operations) valuevalue scopescope

Page 34: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Variable declarationVariable declaration

Variables must always be Variables must always be defined before they before they are used.are used.

datatype identifier;datatype identifier; For exampleFor example

int i; // defines a variable named as i of data type of integer.int i; // defines a variable named as i of data type of integer. float j; // defines a variable named as j of data type of float.float j; // defines a variable named as j of data type of float.

Page 35: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Descriptive variable nameDescriptive variable name DODO use variable names that are descriptive. use variable names that are descriptive.

For example, a program that calculates loan payments could For example, a program that calculates loan payments could store the value of the prime interest rate in a variable named store the value of the prime interest rate in a variable named interest_rate. interest_rate.

The variable name helps make its usage clear. You could also The variable name helps make its usage clear. You could also have created a variable named x or even my_carson; it doesn't have created a variable named x or even my_carson; it doesn't matter to the C compiler. But bad names won’t help others to matter to the C compiler. But bad names won’t help others to read your code. read your code.

Though it might take a little more time to type descriptive Though it might take a little more time to type descriptive variable names, the improvements in program clarity make it variable names, the improvements in program clarity make it worthwhile. worthwhile.

Page 36: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Constant literalsConstant literals

float k=0;float k=0; k=5+56.89; // 5 and 56.89 are called constant k=5+56.89; // 5 and 56.89 are called constant

literalsliterals

Page 37: Syntax of C Programming Language #Lesson 2 Sen Zhang.

#define #define preprocessor directivespreprocessor directives

#define symbol value #define symbol value Will define a constant value. Will define a constant value. It means whenever the symbol appears It means whenever the symbol appears

anywhere in the program after #define is anywhere in the program after #define is introduced, the specified value is substituted in introduced, the specified value is substituted in place of the symbol.place of the symbol.

You only need to modify one place to change You only need to modify one place to change the value of the symbol.the value of the symbol.

Page 38: Syntax of C Programming Language #Lesson 2 Sen Zhang.

ConstantsConstants

#define#define SIZESIZE 100100

int main( )int main( ){{

int i;int i;for (i=0; i< SIZE; i++)for (i=0; i< SIZE; i++)

……}}

Page 39: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Another way to define constant is Another way to define constant is to use const quantifierto use const quantifier

const int SIZE=10;const int SIZE=10;

Page 40: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Constants Constants

constconst int SIZE=100; // global scopeint SIZE=100; // global scope

int main( )int main( ){{

int i;int i;for (i=0; i< SIZE; i++)for (i=0; i< SIZE; i++)

……}}

Page 41: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Constants Constants

int main( )int main( ){{

constconst int SIZE=100; // local scope to mainint SIZE=100; // local scope to main

int i;int i;for (i=0; i< SIZE; i++)for (i=0; i< SIZE; i++)

……}}

Page 42: Syntax of C Programming Language #Lesson 2 Sen Zhang.

Operations on dataOperations on data

OperatorsOperators Built – in library functionsBuilt – in library functions User –defined functionsUser –defined functions

Page 43: Syntax of C Programming Language #Lesson 2 Sen Zhang.

A simple c programA simple c programillustrate many big ideas.illustrate many big ideas.

Page 44: Syntax of C Programming Language #Lesson 2 Sen Zhang.

A simple program get input from keyboard, A simple program get input from keyboard, the do calculation, and output the result!the do calculation, and output the result!

#include <stdio.h> #include <stdio.h> int main() int main() { {

int a, b, c; int a, b, c; printf("Enter the first value:"); printf("Enter the first value:"); scanf("%d", &a); scanf("%d", &a);

printf("Enter the second value:"); printf("Enter the second value:"); scanf("%d", &b); scanf("%d", &b);

c = a + b; c = a + b;

printf("%d + %d = %d\n", a, b, c); printf("%d + %d = %d\n", a, b, c);

return 0; return 0;

} }

Page 45: Syntax of C Programming Language #Lesson 2 Sen Zhang.

How this program works when you How this program works when you execute itexecute it

Page 46: Syntax of C Programming Language #Lesson 2 Sen Zhang.

CommentsComments A comment is text replaced during preprocessing by a single space A comment is text replaced during preprocessing by a single space

character; the compiler therefore ignores all comments.character; the compiler therefore ignores all comments. There are two kinds of comments: There are two kinds of comments:

The /* (slash, asterisk) characters, followed by any sequence of characters (including new The /* (slash, asterisk) characters, followed by any sequence of characters (including new lines), followed by the */ characters. This kind of comment is commonly called a C-style lines), followed by the */ characters. This kind of comment is commonly called a C-style comment. comment.

The // (two slashes) characters followed by any sequence of characters. A new line not The // (two slashes) characters followed by any sequence of characters. A new line not immediately preceded by a backslash terminates this form of comment. This kind of immediately preceded by a backslash terminates this form of comment. This kind of comment is commonly called a single-line comment or a C++ comment. comment is commonly called a single-line comment or a C++ comment.

A C++ comment can span more than one physical source line if it is joined into one A C++ comment can span more than one physical source line if it is joined into one logical source line with line-continuation (\) characters. logical source line with line-continuation (\) characters.

You can put comments anywhere the language allows white space. You can put comments anywhere the language allows white space.

Page 47: Syntax of C Programming Language #Lesson 2 Sen Zhang.

You You cannotcannot nest C-style comments inside nest C-style comments inside other C-style comments. Each comment ends other C-style comments. Each comment ends at the first occurrence of */.at the first occurrence of */.

The /* or */ characters found in a character The /* or */ characters found in a character constant or string literal do not start or end constant or string literal do not start or end comments.comments. Such as “/*” or “*/”, they are not commentsSuch as “/*” or “*/”, they are not comments

Page 48: Syntax of C Programming Language #Lesson 2 Sen Zhang.

You do not need to know at this You do not need to know at this levellevel

You can also include multibyte characters; to You can also include multibyte characters; to instruct the compiler to recognize multibyte instruct the compiler to recognize multibyte characters in the source code, compile with the characters in the source code, compile with the -qmbcs option. option.

Page 49: Syntax of C Programming Language #Lesson 2 Sen Zhang.

ENDEND

Lesson #2Lesson #2