Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter...
-
Upload
bryan-stevenson -
Category
Documents
-
view
223 -
download
4
Transcript of Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter...
Fundamental Data Types, Operators and Expressions
Kernighan/Ritchie:Kelley/Pohl:
Chapter 2Chapter 2, 3
222
Lecture Overview
Variables and data types
Literals and constants
Operators and type conversions
Enumeration and typedef
Library functions – math, strings and I/O
333
Identifiers
The name of a function, variable, or other language construct is called an identifier
Identifiers may contain letters, digits and the underscore ('_') character
An identifier may not begin with a digit
Reserved words cannot be used as identifiers
444
Data Types
C has only two main data types: integer floating point
Each can be preceded by a qualifier,which changes its size or behavior: signed / unsigned short / long
555
Integer Sizes
The basic integer data type is int
Its size is not defined as part of the language (unlike Java), and is machine dependant
The types long int and short int define different integer sizes
Short-cut names: long and short
666
Signed and Unsigned Integers
The qualifiers signed and unsigned can be added before an integer type definition
By default, integers are signed
As with length qualifiers, the int can be dropped, and thus unsigned will definean unsigned int variable
777
The char Data Type
All int types are multiple-byte
To define a single byte variable, the type char is used
char is just like any other integer type, and char and int variables may be assigned to each other freely
char is ASCII, not Unicode
888
The sizeof Operator
The unary operator sizeof returns the number of bytes needed to store a variableof a given type:
It can also be used with a specific variable:
(Equivalent to using the variable's type)
sizeof (type)
sizeof (var)
999
Data Type Sizes
#include <stdio.h>
int main() {
printf ("The size of some fundamental types:\n\n"); printf (" char:%3d byte \n", sizeof(char)); printf (" short:%3d bytes\n", sizeof(short)); printf (" int:%3d bytes\n", sizeof(int)); printf (" long:%3d bytes\n", sizeof(long)); printf (" unsigned:%3d bytes\n", sizeof(unsigned)); printf (" float:%3d bytes\n", sizeof(float)); printf (" double:%3d bytes\n", sizeof(double)); printf ("long double:%3d bytes\n", sizeof(long double));}
101010
Data Type Sizes
The results of running the previous program on one specific machine:
The size of some fundamental types:
char: 1 byte short: 2 bytes int: 4 bytes long: 4 bytes unsigned: 4 bytes float: 4 bytes double: 8 byteslong double: 12 bytes
111111
Lecture Overview
Variables and data types
Literals and constants
Operators and type conversions
Enumeration and typedef
Library functions – math, strings and I/O
121212
Literals
A literal is an explicit value appearing ina program
Literals can represent numbers, charactersor strings
Each literal belongs to a primitive type, and this type can be determined from its format
131313
Literal Types
Integer Decimal Hexadecimal Octal
Floating point Character String
141414
Literal Types
Any single character between single quotes is a character literal
A list of characters between double quotes is a string literal
Any unquoted number belongs either to one of the integer types, or to one of the floating point types
151515
Literal Types
A series of digits with no decimal point isan integer literal An integer literal is int by default, and can be
specified as long by adding an 'L' after it
A series of digits with a decimal point, or followed by an 'F' or by a 'D', is a floating point literal double by default, float if followed by an 'F'
161616
Literal Types – Examples
Literal
1788864L37.26637D87.363F26.77e3'c''&'"Hello""A&*/-?"
Data Type
intlongdoubledoublefloatdoublecharcharchar []char []
171717
Integer Literals In Different Number Bases
Just as the literal suffix defines the data type (int or long), the prefix defines the base (decimal, hexadecimal or octal)
A prefix of 0x stands for hexadecimal
A prefix of 0 stands for octal022, 065, 01
0xFF, 0xA1C, 0x25
181818
Literal Bases – Examples
Literal
1780xAA2502500x10001010
Base
DecimalHexadecimalDecimalOctalDecimalHexadecimalOctalDecimal
191919
Literal Bases – Examples
int main() { printf ("%d %x %o\n", 19, 19, 19); printf ("%d %x %o\n", 0x1c, 0x1c, 0x1c); printf ("%d %x %o\n", 017, 017, 017); printf ("%d\n", 11 + 0x11 + 011); printf ("%x\n", 2097151); printf ("%d\n", 0x1FfFFf); return 0;}
19 13 2328 1c 3415 f 17371fffff2097151
202020
String Literals
A string literal is an array of characters
The internal representation of a string hasa null character '\0' at the end
Therefore, the space required to hold a string is one byte more than its length
212121
Strings and Characters
An implementation of the library function that returns the length of a string:
int strlen (char s[]) {
int i = 0;
while (s[i] != '\0') i++;
return i;}
222222
Constants
A constant is a variable whose value cannot be changed
The compiler will issue a warning if you tryto change the value of a constant
In C, we use the const modifier to declarea constant
const int MONTHS_IN_YEAR = 12;
232323
const and #define
the const modifier creates a variable, with a type and with memory allocation
#define is not much more than a simple text replacement mechanism Saves memory, but has no type checking
const has additional uses, and can also be applied to function parameters or arrays
242424
Lecture Overview
Variables and data types
Literals and constants
Operators and type conversions
Enumeration and typedef
Library functions – math, strings and I/O
252525
Operators
C supports the same operators as Java: Arithmetic Assignment Increment / Decrement Bitwise Relational and Logical
Operator precedence rules are also similar
262626
Operators
Arithmetic operators: +, -, *, /, %
Assignment operators: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Increment / Decrement operators: ++, --
272727
Operators
Bitwise operators: & (and), | (or), ~ (not), ^ (xor),<< (left shift), >> (right shift)
Relational and Logical operators: >, >=, <, <=, ==, !=, &&, ||
282828
Bitwise Operators
Bitwise operators work on specific bits
They have many uses, especially in low level operations Flags – each bit in an integer is a separate flag Compression – using non-standard data type sizes Communication protocols Computer graphics (turning pixels on or off)
292929
Bitwise Operators – Example
#include <stdio.h>
/* Get n bits starting at position p. */unsigned getbits (unsigned x, int p, int n) { return (x >> (p+1-n)) & ~(~0 << n);}
int main (int argc, char *argv[]) { /* Get bits 4,3,2 from 10010110. Result: 101. */ printf ("%d\n", getbits (150, 4, 3)); return 0;}
5
303030
Bitwise Operators – Example
Our goal is to start with bit 4, and take 3 bits to the right (bits 4, 3 and 2): The first shift pushes outside all bits to the right of
the desired section (bits 0 and 1) The second shift creates a mask with n bits in the n
rightmost places Using '&', all bits to the left of the desired section
are zeroed, and only the n rightmost bits are left
313131
Type Conversions
When operands of different types appearin an expression or in an assignment,the smaller is converted into the larger
Assignment or casting may also convert large types into smaller ones
Information loss will not cause a compilation error (possibly a warning)
323232
Converting float and int
#include <stdio.h>
int main() { int i; float f = 3.3;
i = f; f = i;
printf ("i: %d\n", i); printf ("f: %f\n", f);}
i: 3f: 3.000000
333333
Converting char and int
#include <stdio.h>
int main() {
int i; char c = 5;
i = c; c = i;
printf ("c equals: %d\n", c);}
c equals: 5
343434
Converting char and int
#include <stdio.h>
int main() {
int i = 1000; char c;
c = i; i = c;
printf ("i equals: %d\n", i);}
i equals: -24
353535
Converting char and int
#include <stdio.h>int main() { char c; int i;
for (i = 'a'; i <= 'z'; i++) printf ("%c", i) ; /* Print abc ... z */ printf ("\n");
for (c = 65; c <= 90; c++) printf ("%c", c) ; /* Print ABC ... Z */ printf ("\n");}
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
363636
Converting char and int
#include <stdio.h>
int atoi (char s[]) {
int i, n = 0; for (i = 0; s[i] >= '0' && s[i] <= '9'; i++) n = 10 * n + (s[i] - '0');
return n;}
int main() { printf ("%d\n", 1 + atoi ("345999"));}
346000
373737
Type Conversion in Function Calls
Function calls can also trigger a conversion of the parameter or the return value#include <stdio.h>
void f (int p) { printf ("%d\n", p);}
int main() { f (3.3); return 0;}
3
383838
Lecture Overview
Variables and data types
Literals and constants
Operators and type conversions
Enumeration and typedef
Library functions – math, strings and I/O
393939
The use of typedef
typedef allows the programmer to associate a type with an identifier
Creates types that reflect the intended use
Can help in porting the program
The format is similar to that of a variable declaration:typedef type identifier
404040
typedef – Example
#include <stdio.h>
typedef int Inches, Feet;typedef char String[];
int main() { Feet input_feet; Inches input_inches; String message = "Please enter length:\n";
printf (message); scanf ("%d %d", &input_feet, &input_inches);
printf ("The length is: %d'%d\"\n", input_feet, input_inches);}
414141
typedef – Example
The same program without typedef:int main() {
int input_feet; int input_inches; char message[] = "Please enter length:\n";
printf (message); scanf ("%d %d", &input_feet, &input_inches);
printf ("The length is: %d'%d\"\n", input_feet, input_inches);}
424242
Enumeration Types
Enumeration types are another way of defining constants
Provides a way of defining a set of values Enumeration constants are of type int Each has a numeric value, starting with 0, and
increasing by 1 with each value Other values can be defined explicitly
434343
Enumeration Types
Defines an enumeration for week days
This defines the enumeration Fruit, and declares lunch as a variable of that type
The values of the constants are:APPLE=0,PEAR=1,ORANGE=3,LEMON=4
enum Day {SUN, MON, TUE, WED, THU, FRI, SAT};
enum Fruit {APPLE, PEAR, ORANGE = 3, LEMON} lunch;
444444
typedef and enum – Example
#include <stdio.h>enum Color {RED, GREEN, BLUE};typedef enum {TRUE = 1, FALSE = 0} Boolean;
int main() { enum Color favorite; Boolean is_favorite = TRUE;
printf ("sizeof(favorite): %d\n", sizeof(favorite)); favorite = GREEN; printf ("RED: %d\n", RED); printf ("favorite: %d\n", favorite);
if (is_favorite) printf ("Green is my favorite color!\n");}
454545
Lecture Overview
Variables and data types
Literals and constants
Operators and type conversions
Enumeration and typedef
Library functions – math, strings and I/O
464646
getchar() and putchar()
getchar() and putchar() are used to read and write single characters from/to the standard input/output
They are defined in stdio.h
In order to signal the end of a file, we need an additional value that is not a character
To hold this value, an int must be used
474747
getchar() and putchar() – Example
#include <stdio.h>
int main() { int c;
while ((c = getchar()) != EOF) if (c >= 'a' && c <= 'z') putchar (c + 'A' - 'a'); else putchar (c); return 0;}
> The date is: NOVEMBER 2006THE DATE IS: NOVEMBER 2006
484848
Additional Functions forReading Characters
getc() and putc() are similar to getchar() and putchar(), accept that they read from any file
FILE and EOF are defined in stdio.h Both functions return an EOF on failure
int getc (FILE *fp)
int putc (int c, FILE *fp)
494949
Reading Complete Lines
The standard I/O library also includes functions for handling complete lines
fgets() reads at most n-1 characters from the file associated with fp
The line is read into line, and a '\0' is inserted at the end, after the '\n'
char *fgets (char *line, int n, FILE *fp)
505050
Reading Complete Lines
fgets does not allocate memory to store the result, so line should point to a buffer large enough to contain the complete line Two additional spaces should be reserved beyond
the text itself, for '\n' and '\0'
If there are no more lines to read, then NULL is returned
515151
Example – Adding Line Numbersto a Text File
#include <stdio.h>
#define MAX_LINE_SIZE 80
int main() {
char buf[MAX_LINE_SIZE]; int line = 1;
while (fgets (buf, MAX_LINE_SIZE, stdin) != NULL) printf ("%4d %s", line++, buf);
return 0;}
525252
Formatted Input and Output with Files
The functions printf() and scanf() have special versions for accessing files
The file versions have the same format and arguments as the standard versions
is the same as
int fprintf (FILE *fp, const char *format, …)
int fscanf (FILE *fp, const char *format, …)
fprintf (stdout, …) printf (…)
535353
Formatted Input and Outputwith Strings
Similarly, the standard I/O functions have special versions that work with strings
The function sprintf() writes to its first argument instead of writing to the screen
sscanf() reads from the input string s
int sprintf (char *s, const char *format, …)
int sscanf (const char *s, const char *format, …)
545454
Formatted Input and Outputwith Strings – Example
#include <stdio.h>
int main() { char *str1 = "1234 12.5 hello"; char str2[80], str3[80]; float f; int i;
sscanf (str1, "%d %f %s", &i, &f, str2); sprintf (str3, "str %s, int %d, float %.2f", str2, i, f); printf ("Result: %s\n", str3);}
Result: str hello, int 1234, float 12.50
555555
String Functions
The standard library contains many functions for handling strings
The prototypes of these functions are defined in the header file string.h
An example we have seen earlier:
size_t is defined as an integral type
size_t strlen (const char *s)
565656
Mathematical Functions
The C language itself does not include any mathematical functions, but these can be obtained from the mathematics library
To use functions from the library, the math.h header should be included
Also, in some versions of UNIX, the -lm option must be passed to the compiler
575757
Mathematical Functions
Math functions accept double arguments, and return double values
Some functions from the math library: sqrt(), pow() exp(), log() sin(), cos(), tan()
585858
Mathematical Functions – Example
#include <stdio.h>#include <math.h>int main() { float x; printf ("Input x: "); scanf ("%f", &x); printf (" x = %.3f\n" " sqrt (x) = %.3f\n" " pow (x, x) = %.3f\n", x, sqrt (x), pow (x, x));}
Input x: 3 x = 3.000 sqrt (x) = 1.732 pow (x, x) = 27.000