Вы находитесь на странице: 1из 10

Programming Language: Syntax

Syntax is the grammar of the language


„ Analogous to rules in English Language
¾ Missing
ss g a pe
period
od a
after
e se
sentence
e ce
¾ Rules using verbs, nouns etc..
Introduction to C Language
Overview, variables, Operators, Statements
„ Most languages provide syntax check errors
(Interprets/Compilers)
¾ Syntax error messages may be helpful
¾ Often,
Often they are not
¾ You gain experience with error messages after a while
Based on slides © McGraw-Hill
Additional material © 2004/2005 Lewis/Martin
Modified by Diana Palsetia

CIT 593 2

Programming Language Semantics C Programs are Compiled


When the computer carries out your instructions (program)
„ Running or Executing a program (text file containing
hello.c
C source code)
Semantics is the meaning of the program
„ We learn the semantics after we run or execute the program
„ Basically we observe the output

(text file containing


After the executing program, the semantics of the program hello.s
may or may be correct assembler source code)

Semantic errors cause your answers to be wrong


„ You may or may not get error messages hello
¾ E.g. Error Message – Dividing a number by zero (binary executable file
(a.out)
„ If your program is not doing what you want it to do, though it Containing machine code )
runs, the error is semantic
We will use the GNU gcc compiler (v4.0 and higher)
CIT 593 3 CIT 593 4

1
Syntax Compiling and Executing C programs Compilation Process
C
In the folder that contains the source code do for: Entire mechanism is usually called the compiler Source and
Header Files

Preprocessor
„ Acts upon C preprocessor directives
Compiling the program „ “Source-level” transformations C Preprocessor

gcc –Wall progname.c ¾ Output is still C


 gcc tool for compiling process Compiler

 -Wall to display all warning


Compiler Source Code
Analysis
„ Generates object (.o) file for each file Symbol Table
 progname.c is file that contains C code
¾ Machine instructions (binaries) Target Code
Synthesis
 Will produce a file called a.out „ This file is not seen unless special
compiler options are used
Library
Executing Object Files
Linker

Linker
 ./a.out
„ Combine object files (including libraries)
Executable
into executable image 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 programmer performs an operation
„ A named space in memory
„ Can span multiple lines „ E.g. z, counter

Operators
p
„ 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;
 Syntax:<type> <identifier>
}
Every C program must have the above format to develop
Later we will discuss:
application program(s)
„ One of files must contain above structure Scope: is the region of the program in which the variable is
¾ main is a special function in C alive and accessible
¾ similar to Java’s main method
„ Starting point for every program Storage: how C compiler allocates storage and whether or
All C programs start and finish execution in the main not the variable loses its value when the section that
Note: int main(int argc, char **argv) – main function can contains it has completed execution
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_pper_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 library 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 Data Type
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
„ So how do I know the size?
„ This is done by appending “const” before the type
¾ Use unary operator called sizeof. E.g. sizeof(int)
– returns answer in bytes
Symbol
Signed vs. unsigned:
„ Like constants but is preprocessor directive
„ Default is 2’s complement signed integers
„ Use “unsigned” keyword for unsigned numbers
CIT 593 13 CIT 593 14

Literals C program showing Basic Syntax


Integer #define RADIUS 15.0
123 /* decimal */ symbol
-123 int main(){
0x123 /* hexadecimal */ double area;
double circum; Declaration
D l ti a variable
i bl (declaration statement)
Floating point
const double PI = 3.14159;
6.023
constant literal
6.023e23 /* 6.023 x 1023 */
5E12 /* 5.0 x 1012 */ area = PI * RADIUS * RADIUS;
Expression
p
Character circum = 2 * PI * RADIUS;
'c'
Statement
'\n' /* newline */ return 0; Operators
'\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 literals, variables, constants,
operators, and function calls
„ Every expression has a type
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
„ Used for values that won't change during execution,
PI * RADIUS * RADIUS;
but might change if the program is reused(Must x + sqrt(y) //sqrt is function with input y
recompile)
x % 6 == 0

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
Simple statement ends with semicolon (note: “;” is not a „ What does it do?
comment
co e t in C)
(2) Precedence
z = x * y; /* assign product to z */ „ In which order are operators combined?
y = y + 1; /* update y */ „ Example:
"a * b + c * d" is the same as "(a * b) + (c * d)"
; /* null statement */ because multiply (*) has a higher precedence than addition (+)
sqrt(y); /* containing a function call*/
(3) Associativity
Compound statement formed with braces „ In which order are operators of the same precedence combined?
„ Syntactically equivalent to a simple statement „ 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
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
2. Set value of left-hand side variable to result. side
¾ Type conversion might make assigned value
different than computed value e.g. int x = 15.6/3 = 5

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);

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 6 l-to-r „ if x is int, converted to double and result is double
/ divide x / y 6 l-to-r
Integer
g division -- fraction is dropped
pp
% modulo x % y 6 l-to-r „ Example: x / 3
„ if x is int and x=5, result is 1 (not 1.666666...)
+ addition x + y 7 l-to-r
- subtraction x - y 7 l-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 + - „ Th C h
Thus has lless ttype safety
f t features
f t compared
d to
t Java
J
Example
„2+ 3 * 4 vs. (2 + 3) * 4 Modulo -- result is remainder
„ Example: x % 3
„2* 4% 5
„ if x is int and x=5, result is 2

CIT 593 23 CIT 593 24

6
Relational Operators AND, OR, NOT
Symbol Operation Usage Precedence Assoc Two states: TRUE=1, FALSE=0
> greater than x > y 9 l-to-r
>= greater than or equal x >= y 9 l-to-r A B A AND B A B A OR B A NOT A
< less than x < y 9 l-to-r 0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
<= less than or equal x <= y 9 l-to-r
1 0 0 1 0 1
== equal x == y 10 l-to-r 1 1 1 1 1 1
!= not equal x != y 10 l-to-r
View n
n-bit
bit number as a collection of n logical values
Result is non-zero (TRUE) or zero (FALSE) „ Operation applied to each bit independently (bitwise
operators)
„ No boolean data type in C
¾ Applications e.g. water marking, cryptography
„ All logical work is done via integer data type

CIT 593 25 CIT 593 26

Logical Operators Relational and Logical Usage


Symbol Operation Usage Precedence Assoc Typically used to construct conditions
„ Ultimately conditional will result in TRUE or FALSE
! logical NOT !x 4 r-to-l „ No Boolean type
&& logical AND x && y 14 l-to-r ¾ Outcome is zero or non-zero (i.e. int)
|| logical OR x || y 15 l to r
l-to-r Example
„ (x > y) && (x < z)
„ (c == ‘q’) || (c == ‘Q’)

Logical Operator is different from bitwise operators Conditions allow change in the control flow
„ Can skip certain instructions based on condition
„ Treats entire variable (or value) as TRUE (non-zero), or
FALSE (zero) if((c == ‘q’) || (c == ‘Q’)){
„ E.g.
Eg 1 && 8 = 1 (True && True = True) //Quit game
}

„ 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

CIT 593 27 CIT 593 28

7
Bitwise Operators
Examples of Bitwise AND, OR, NOT
Symbol Operation Usage Precedence Assoc
~ bitwise NOT ~x 4 r-to-l AND
11000101
<< left shift x << y 8 l-to-r „ Useful for clearing bits
>> right shift x >> y 8 l-to-r ¾ AND with zero = 0 AND 00001111
& bitwise AND x & y 11 l-to-r ¾ AND with one = no change 00000101
^ bitwise XOR x ^ y 12 l-to-r
| bitwise OR x | y 13 l-to-r
OR 11000101
Bit-wise vs Logical AND „ Useful for setting bits OR 00001111
„ 1 & 8 = 0 (000001 AND 001000 = 000000) ¾ OR with zero = no change
„ 1 && 8 = 1 (True && True = True) ¾ OR with one = 1 11001111

NOT
NOT 11000101
„ Unary operation -- one argument
00111010
„ Flips every bit
CIT 593 29 CIT 593 30

Shift Operator: << (Left Shift Operator) …C and the Right Shift Operator (>>)
Operate on values -- neither operand is changed Does right shift sign extend or not?
„ Answer: Yes and No
Left Shift (<<)
variable << shift amount Unsigned
g values: zero extend
„ Shifts bits to the left by shift amount „ unsigned int x = ~0;
„ Fills spaces equivalent to shift amount on the right side „ Then, (x >> 10) will have 10 leading zeros
with zeroes
„ x = y << 1 same as x = y + y or 2 * y
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
¾ int x = ~0; /* signed */
¾ Then, (x >> 10) will still be all 1s
CIT 593 31 CIT 593 32

8
Special Operators: ++ and -- Using ++ and --
Changes value of variable by 1 before (or after) its x = 4;
value is used in an expression y = x++;
Results: x = 5, y = 4
Symbol Operation Usage PrecedenceAssoc (b
(because x iis iincremented
t d after
ft assignment)
i t)
++ postincrement x++ 2 r-to-l
-- postdecrement x-- 2 r-to-l x = 4;
++ preincrement ++x 3 r-to-l y = ++x;
-- predecrement --x
x 3 rr-to-l
to l Results: x = 5, y = 5
(because x is incremented before assignment)
Pre: Increment/decrement variable before using its value
Post: Increment/decrement variable after using its value

CIT 593 33 CIT 593 34

Special Operators: +=, *=, etc. Input and Output


Arithmetic and bitwise operators can be combined Variety of I/O functions in C Standard Library
with assignment operator „ Libraries contain code/programs already written that can be re-used
„ So we do not have to re-invent the wheel
Statement Equivalent assignment
x += y; x = x + y; For I/O, must include <stdio.h>
stdio.h i.e.#include <stdio.h>
x -= y; x = x - y; ¾ Must go above the main function syntax
„ #include is a C processor Directive
x *= y; x = x * y; ¾ Before compiling, copy contents of stdio.h into source code
x /= y; x = x / y; ¾ .h files typically contain descriptions of functions and
structs
x %= y; x = x % y;
All have same
x &= y; x = x & y; printf – Print formatted
precedence and „ Performs output to standard output device (monitor)
x |= y; x = x | y; associativity as = „ String contains characters to print and formatting directions for variable
x ^= y; x = x ^ y; and associate „ Really useful in debugging
x <<= y; x = x << y; right-to-left.
x >>= y; x = x >> y; scanf – Scan Formatted
„ String contains formatting directions for reading input

CIT 593 35 CIT 593 36

9
Output Examples
printf(“Counter value is %d\n", counter);
„ print the variable counter as a decimal integer, followed by a
linefeed (\n)
This code:
„ Linefeed will make the cursor go onto next line printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n",
Can print arbitrary expressions, not just variables 43+59);
3 9
printf("%d\n", startPoint - counter); printf("43 plus 59 in hex is %x.\n",
43+59);
printf("43 plus 59 as a character is
Print multiple expressions with a single statement %c.\n", 43+59);
printf("%d %d\n", counter, startPoint - counter);

Different formatting options: produces this output:


%d decimal integer 43 is a prime number.
%x hexadecimal integer 43 plus 59 in decimal is 102.
%c ASCII character 43 plus 59 in hex is 66.
%f floating-point number 43 plus 59 as a character is f.
CIT 593 37 CIT 593 38

Examples of Input
scanf("%d", &startPoint);
„ 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);
„ reads a single character and stores it in nextChar
scanf("%f", &radius);
„ reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
„ 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 39

10

Вам также может понравиться