Download presentation
Presentation is loading. Please wait.
Published byBryan Stevenson Modified over 9 years ago
1
Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter 2, 3
2
222 Lecture Overview Variables and data types Literals and constants Operators and type conversions Enumeration and typedef Library functions – math, strings and I/O
3
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
4
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
5
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
6
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 define an unsigned int variable
7
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
8
888 The sizeof Operator The unary operator sizeof returns the number of bytes needed to store a variable of a given type: It can also be used with a specific variable: (Equivalent to using the variable's type) sizeof (type) sizeof (var)
9
999 Data Type Sizes #include 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)); }
10
10 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 bytes long double: 12 bytes
11
11 Lecture Overview Variables and data types Literals and constants Operators and type conversions Enumeration and typedef Library functions – math, strings and I/O
12
12 Literals A literal is an explicit value appearing in a program Literals can represent numbers, characters or strings Each literal belongs to a primitive type, and this type can be determined from its format
13
13 Literal Types Integer Decimal Hexadecimal Octal Floating point Character String
14
14 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
15
15 Literal Types A series of digits with no decimal point is an 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 '
16
16 Literal Types – Examples Literal 178 8864L 37.266 37D 87.363F 26.77e3 'c' '&' "Hello" "A&*/-?" Data Type int long double float double char char []
17
17 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 octal 022, 065, 01 0xFF, 0xA1C, 0x25
18
18 Literal Bases – Examples Literal 178 0xAA 25 025 0 0x10 0010 10 Base Decimal Hexadecimal Decimal Octal Decimal Hexadecimal Octal Decimal
19
19 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 23 28 1c 34 15 f 17 37 1fffff 2097151
20
20 String Literals A string literal is an array of characters The internal representation of a string has a null character ' \0 ' at the end Therefore, the space required to hold a string is one byte more than its length
21
21 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; }
22
22 Constants A constant is a variable whose value cannot be changed The compiler will issue a warning if you try to change the value of a constant In C, we use the const modifier to declare a constant const int MONTHS_IN_YEAR = 12;
23
23 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
24
24 Lecture Overview Variables and data types Literals and constants Operators and type conversions Enumeration and typedef Library functions – math, strings and I/O
25
25 Operators C supports the same operators as Java: Arithmetic Assignment Increment / Decrement Bitwise Relational and Logical Operator precedence rules are also similar
26
26 Operators Arithmetic operators: +, -, *, /, % Assignment operators: =, +=, -=, *=, /=, %=, &=, |=, ^=, >= Increment / Decrement operators: ++, --
27
27 Operators Bitwise operators: & (and), | (or), ~ (not), ^ (xor), > (right shift) Relational and Logical operators: >, >=, <, <=, ==, !=, &&, ||
28
28 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)
29
29 Bitwise Operators – Example #include /* 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
30
30 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
31
31 Type Conversions When operands of different types appear in 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)
32
32 Converting float and int #include int main() { int i; float f = 3.3; i = f; f = i; printf ("i: %d\n", i); printf ("f: %f\n", f); } i: 3 f: 3.000000
33
33 Converting char and int #include int main() { int i; char c = 5; i = c; c = i; printf ("c equals: %d\n", c); } c equals: 5
34
34 Converting char and int #include int main() { int i = 1000; char c; c = i; i = c; printf ("i equals: %d\n", i); } i equals: -24
35
35 Converting char and int #include 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"); } abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
36
36 Converting char and int #include 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
37
37 Type Conversion in Function Calls Function calls can also trigger a conversion of the parameter or the return value #include void f (int p) { printf ("%d\n", p); } int main() { f (3.3); return 0; } 3
38
38 Lecture Overview Variables and data types Literals and constants Operators and type conversions Enumeration and typedef Library functions – math, strings and I/O
39
39 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
40
40 typedef – Example #include 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); }
41
41 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); }
42
42 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
43
43 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;
44
44 typedef and enum – Example #include 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"); }
45
45 Lecture Overview Variables and data types Literals and constants Operators and type conversions Enumeration and typedef Library functions – math, strings and I/O
46
46 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
47
47 getchar() and putchar() – Example #include 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 2006 THE DATE IS: NOVEMBER 2006
48
48 Additional Functions for Reading 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)
49
49 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)
50
50 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
51
51 Example – Adding Line Numbers to a Text File #include #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; }
52
52 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 (…)
53
53 Formatted Input and Output with 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, …)
54
54 Formatted Input and Output with Strings – Example #include 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
55
55 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)
56
56 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
57
57 Mathematical Functions Math functions accept double arguments, and return double values Some functions from the math library: sqrt(), pow() exp(), log() sin(), cos(), tan()
58
58 Mathematical Functions – Example #include 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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.