580 likes | 747 Views
Fundamental Data Types, Operators and Expressions. Kernighan/Ritchie: Kelley/Pohl:. Chapter 2 Chapter 2, 3. Lecture Overview. Variables and data types Literals and constants Operators and type conversions Enumeration and typedef Library functions – math, strings and I/O. Identifiers.
E N D
Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter 2, 3
Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O
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
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
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
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
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
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)
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)); }
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
Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O
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
Literal Types • Integer • Decimal • Hexadecimal • Octal • Floating point • Character • String
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
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 floatingpoint literal • double by default, float if followed by an 'F'
Literal Types – Examples Literal 178 8864L 37.266 37D 87.363F 26.77e3 'c' '&' "Hello" "A&*/-?" Data Type int long double double float double char char char [] char []
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 0xFF, 0xA1C, 0x25 022, 065, 01
Literal Bases – Examples Literal 178 0xAA 25 025 0 0x10 0010 10 Base Decimal Hexadecimal Decimal Octal Decimal Hexadecimal Octal Decimal
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
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
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; }
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;
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
Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O
Operators • C supports the same operators as Java: • Arithmetic • Assignment • Increment / Decrement • Bitwise • Relational and Logical • Operator precedence rules are also similar
Operators • Arithmetic operators: • +, -, *, /, % • Assignment operators: • =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= • Increment / Decrement operators: • ++, --
Operators • Bitwise operators: • & (and), | (or), ~ (not), ^ (xor),<< (left shift), >> (right shift) • Relational and Logical operators: • >, >=, <, <=, ==, !=, &&, ||
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)
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
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
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)
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: 3 f: 3.000000
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
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
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"); } abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
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
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
Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O
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 typeidentifier
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); }
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); }
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
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;
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"); }
Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O
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
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 2006 THE DATE IS: NOVEMBER 2006
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)
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)
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