1 / 58

Fundamental Data Types, Operators and Expressions

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.

edric
Download Presentation

Fundamental Data Types, Operators and Expressions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Fundamental Data Types, Operators and Expressions Kernighan/Ritchie: Kelley/Pohl: Chapter 2 Chapter 2, 3

  2. Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O

  3. 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. 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. 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. 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

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

  9. 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)); }

  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. Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O

  12. 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

  13. Literal Types • Integer • Decimal • Hexadecimal • Octal • Floating point • Character • String

  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. 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'

  16. 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 []

  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 0xFF, 0xA1C, 0x25 022, 065, 01

  18. Literal Bases – Examples Literal 178 0xAA 25 025 0 0x10 0010 10 Base Decimal Hexadecimal Decimal Octal Decimal Hexadecimal Octal Decimal

  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. 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

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

  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. Lecture Overview • Variables and data types • Literals and constants • Operators and type conversions • Enumeration and typedef • Library functions – math, strings and I/O

  25. Operators • C supports the same operators as Java: • Arithmetic • Assignment • Increment / Decrement • Bitwise • Relational and Logical • Operator precedence rules are also similar

  26. Operators • Arithmetic operators: • +, -, *, /, % • Assignment operators: • =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= • Increment / Decrement operators: • ++, --

  27. Operators • Bitwise operators: • & (and), | (or), ~ (not), ^ (xor),<< (left shift), >> (right shift) • Relational and Logical operators: • >, >=, <, <=, ==, !=, &&, ||

  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. 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

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

  32. 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

  33. 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

  34. 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

  35. 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

  36. 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

  37. 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

  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. 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

  40. 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); }

  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. 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. 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. 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"); }

  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. 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. 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

  48. 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)

  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. 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

More Related