1 / 50

C 程式語言

C 程式語言. Learn how to write C programs Data Types Program Structures Input/Output and Files Preprocessing Compile  Link  Execute (Visual C++ 6.0). Prepared by Dr.Konstantin Degtiarev, 11.02.2000. C Programming Language Introduction 1. Information about the course

vinson
Download Presentation

C 程式語言

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. C 程式語言 • Learn how to write C programs • Data Types • Program Structures • Input/Output and Files • Preprocessing • Compile  Link  Execute (Visual C++ 6.0)

  2. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction1 Information about the course • 1 hour lecture + 2 hours lab per week • Lab Attendance and Performance[10%] • 8 laboratory assignments[20%] • 1 midterm examination[30%] • 1 final examination[30%] Textbook:Teach Yourself C, 3rd Edition by Herbert Schildt, McGraw-Hill, Inc., 1999 (ISBN: 0-07-882311-0). A copy of slides + extra materials are available from http://www.cs.ccu.edu.tw/~pahsiung/courses/introCS/

  3. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction2 General information • A programming language is a language that is used by a person to express a process by which a computer can solve a problem • A language is organized around a particular conceptual model - once a language has been developed conceptually, it must be implemented • Implementation of a language means that its basic structures should be represented at the level of bits • A programming language is an abstractionwhich expresses the steps of specification in the form which is converted bytranslator into set of computer instructions

  4. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming Language Introduction3 Programming languages studying. What are the aims? • to understandbetter the functioning and implementation of the structures in different languages • to choose a suitable language for the project (two different classes of problems may require different levels of abstraction) • to learn new capabilities of existing languages Classification of languages • imperative languages (e.g. Pascal, C/C++, Fortran) • non-imperative languages (e.g. Prolog, LISP)

  5. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction4 Translation process and its main stages (all stages are machine-dependent) • lexical analysis (scanning) identifies sequences of characters (tokens) which represent values, identifiers, operators, etc. • syntactic analysis (parsing) identifies valid sequences of characters (statements, expressions) and rejects invalid ones • semantic analysis “assigns” a meaning to identified entities Translators can be in the form of interpreter or compiler(in most cases when semantic analysis is finished compilers perform code optimization)

  6. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction5 Compilation, linking & loading • Compiling is a process of translation of a source code into machine-dependent object code • Linking is a process which combines two or more separate object programs and supplies the information needed to resolve references between them (independently compiled code is “linked” into a single load module) • Loading is a process which brings the object program into memory and starts its execution • Modern programming environments combine a set of tools (editor + compiler + linker + loader+ testing tools + …) into a unique package

  7. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction6 Compilation, linking & loading • Many programming languages allow You to write different pieces of code (modules) separately, and after their compilation linker put these modules together • Linker also replaces symbolic addresses with real memory addresses • Library is a set of precompiled routines that are stored in the object format • Loader is an OS utility (mostly, You can’t directly execute it) that copies programs from the storage device to the main memory, adjusting properly addresses

  8. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction7 Language portability • A language is portable if its programs can be compiled and run on different types of computers without rewriting a source code • C is potentially one of the most portable programming languages. Most C compilers (Borland, Microsoft, Symantec, Watcom, etc.) provide useful extentions(additional features) that are not a part of the C standard • Organizations which prepare and revise standards for languages: American National Standards Institute (ANSI) International Standards Organization (ISO) Institute of Electrical and Electronics Engineers (IEEE)

  9. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction8 Brief comments on C++ • C language  extensions: «C with classes» (Bjarne Stroustrup)  C++ language (1984) • C++ sits on the shoulders of C language (from a B.Stroustrup’s keynote address to ANSI C++ committee in 1989: «C++ is an engineering compromise», and it must be kept «as close as possible to C, but no closer») • C++ (power and efficiency of C) + features that support object-oriented programming (OOP) + type safety & high expressiveness • C++ is quite complex and more difficult to master than C • C++ introduces a new paradigm (model of programming)

  10. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction9 Brief comments on C++ • At the same time, C++ fully supports traditional procedural programming style (process-oriented paradigm) - it means that C++ is a multiparadigm programming language • I know C, so C++ is somewhat clear as well? Unfortunately, NOT exactly… Most probably, You know ANSI C subset of C++ (even without clear understanding of C and C++ incompatibilities!) • The main concepts of Object-Oriented Programming (OOP): Data AbstractionClass/Object EncapsulationInheritance

  11. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction10 Brief comments on C++ • If You want to know more about history of C++, see the following book: «The Design and Evolution of C++» by B.Stroustrup (1994, Addison-Wesley) Further reading: «Practical C++ Programming»(Nutshell Handbook)by S.Qualline (1995, O’Reilly & Associates) «The C++ Programming Language» by B.Stroustrup (2000, Addison-Wesley) Now we start with C language...

  12. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction11 Origins of C language • 1964-1970: Basic Combined Programming Language (BCPL), project Multics (UNIX operating system) • 1970-1973:NB (New B) as a modification of B language and appearance of C language (Dennis Ritchie) • 1973-1978: the kernel of OS UNIX for PDP-11 was rewritten in C; changes in the language and appearance of the first book on C (“The C programming language” by B.Kernighan and D.Ritchie; it is now known as ‘K&R C’) • 1978-1985: C compilers became available on different machine architectures • 1983-1990: ANSI established committee X3J11 with a “goal of producing a C standard”; (standard ISO/IEC 9899-1990)

  13. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageIntroduction12 C language keywords • C is very “compact” language (32 keywords in ANSI C = 27 keywords in K&R C + 5 keywords which were added by ANSI committees) auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while All keywords are lowercase!

  14. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageFirst examples1 Example 1 #include<stdio.h> /* C */ int main(void) { printf(“the\n first\n program in course”); return 0; } #include<iostream.h> // C++ this is one line comment int main( ) { cout <<“the\n first\n program” <<“ in course” << endl; return 0; }

  15. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageFirst examples2 #include<stdio.h>Example 1A int main(void) { printf(“the first output line.”); printf(“the second output line”); return 0; } #include<stdio.h> Example 2 int main(void) { int my_variable = 65; printf(“the value is %d\n”, my_variable); printf(“ and the other result is %c”, my_variable); return 0; }

  16. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageFirst examples3 printf(“the value is %d\n”, my_variable); #include<stdio.h>Example 3 main(void) { int i = 0; while(++i <= 9) { if(i == 5) continue; printf(“the result is %d”,i); } return 0; } format specifier list of variables control string PAY attention !

  17. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageFirst examples4 Example 3A #include <stdio.h> int main(void) { int sqrs[10]; int i; for(i=1; i<11; i++) sqrs[i-1] = i*i; for(i=0; i<10; i++) printf(”%d ”, sqrs[i]); return 0; } array sqrs[ ] consists of 10 elements indices start with 0 !

  18. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageFirst examples5 #include<stdio.h> Example 4 #include<string.h> int main(void) { int index; char stuff[15], *pt; strcpy(stuff,”Test string…”); pt = stuff; /* character by character printing of string */ for(index = 0; index < 15; index++) { printf(“_ %c”, *pt); pt++; } return 0; } PAY attention ! result: _T_e_s_t_ _s_t_r_i_n_g_._._._

  19. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageFirst examples6 Example 4A #include<stdio.h> int a,b,c; int sum(int x, int y); int main(void) /* simple program calculates */ { /* the sum of two integers */ printf(“enter the 1st number: “); scanf(“%d”, &a); printf(“enter the 2nd number: “); scanf(“%d”, &b); c = sum(a,b); /* a call to the function sum( ) is done here */ printf(“\nthe result of %d + %d” “ is %d\n”, a,b,c); return 0; } /* definition of the function which calculates a sum of two integers */ int sum(int x, int y) { return(x+y); } /* end of the function’s body */ function prototype provides the C compiler with a necessary information about the function PAY attention ! (absence of semicolon)

  20. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageExplanations1 Functions are central to C/C++ programming • A function is an independent section of program code that performs a certain task and has been assigned a name • Function main( ) is the only component which is required in every C/C++ program Library functions (purchased as a part of the C compiler package or from the other vendors) Functions User-defined functions (created by a programmer)

  21. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types1 Concept of data types determines … • a set of values of objects (variables) of particular type • a set of operations which can be applied to these objects (their values) • the size of memory used for storing the values of objects • the way a bits combination which corresponds to internal representation of values is interpreted 5 basic types in C language char int float double void + 4 format modifiers:signed unsigned short long

  22. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types2 Some useful remainders on types... • different values have varying memory storage requirements • the size of the data types can vary depending on the computer platform used • ANSI guarantees the following simple rules: • sizeof(char)  1 byte • sizeof(short)  sizeof(int),short  short int • sizeof(int)  sizeof(long),long  long int • sizeof(unsigned)  sizeof(int),unsigned  unsignedint • sizeof(float)  sizeof(double) • before a variable is used in a C program, it must be declared: typename variable_name;

  23. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types3 typedef and constants... • by means of using keyword typedef a new name (synonym) for existing type is created (note, NOT a new type! ): typedef int integer;/* integer is synonym for int */ integer my_variable = 15; /* the variable is defined - that is, declared and initialized */ • the value stored in a constant (unnamed constant) can’t be changed during program’s execution: 0.123 15. -7.139 • floating-point constants can be written in scientific notation as well (1.12e-3  0.00112) literal floating-point constants are treated by C compiler as a double-precision numbers

  24. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types4 more on constants… • a literal constant written without decimal point is represented by the compiler as an integerconstant: -11 153 +638 043 0x84 0X137 const long tum = 12345678; decimal integer constants octal(base 8) integer constant start with a leading zero (0) hexadecimal (base 16) integer constants start with a leading 0x or 0X tum is a symbolic constant

  25. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types5 more on constants and types… • C compiler fits a numeric constant into a smallest compatible data type, but a programmer can specify a desired type explicitly by using a suffix notation: 135 135U (135u) 135UL (135ul) 135.17 135.17F (135.17f) • In C programs You can use three floating-point types: float, double and long double (the default working type in C is double) constant of the type int (by default) constant of the type unsignedint constant of the type float ?

  26. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types6 more on constants and types… Example 4A #include<stdio.h> int main(void) { printf(“the first result is %.11f\n”, 135.1737f/34); printf(“the second result is %.11f”, 135.1737/34); return 0; } • float type provides 6-7 significant digits (precision) mantissa - 23 bits • double type - 15-16 significant digits (precision) mantissa - 52 bits format specifier %f stands for both float and double values result: the first result is 3.97569723690 the second result is 3.97569705882

  27. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types7 more and more on constants and types… Example 5 #include<stdio.h> int main(void) { int variable = 15; printf(“1. result: %d %o\n”, 012*variable, 12*variable); printf(“2. result: %d\n”, 0xA*variable); printf(“3. result: %#x %#o”, 015, 0Xd); printf(“\n4. result: %#X”, 10); return 0; } %#x (%#X) means that a corresponding hexadecimal value is displayed with a prefix 0x (0X); %#o for octal values “brings” prefix 0 PAY attention to the hash mark (pound sign) # in format specifiers result: 1. result: 150 264 2. result: 150 3. result: 0xd 015 4. result: 0XA

  28. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types8 even more on constants and types… • enumeration - a set of symbolic constants (named integers) which form all the valid values of declared type: enum game {socker, cricket, golf, baseball} var1, var2; • tag and list of variables are optional • the previous declaration means that variables var1 and var2are ofthe typeenum gameand their possible values are listed as enumerators(see the list in curly brackets) • each enumeratorinternally is represented as an integer constant value (by default, socker  0, cricket 1, … etc.) list of variables list of enumerators tag keyword

  29. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types9 much more on constants and types… • default correspondence of enumerators to integers can be changed explicitly enum game { socker, cricket = 10, golf, baseball = -5 }; enum game var1, var2; ….. ….. ….. ….. ….. ….. ….. printf(“output is %d and %d”, socker, baseball); printf(“what is it? %s”, golf); ….. (!) specifier %s determines a format of character string stands for 11 (the previous value +1) values 0 and -5 appear in the output requires stdio.h header file something very strange (garbage) in the output ...

  30. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types10 much more on constants and types… • String constant is a sequence of characters enclosed in a pair of double quotes (“) • String( VAR a: string[25];) data type which is supported by Turbo Pascal is formally absent in C language ‘m’character constant (enclosed in single quotes) “m”string constant (internally represented by 2 bytes) “example/*goes on”string constant (recognized by the C compiler as a single token) \n backslash character constant (escape sequence) which represents “newline” (recognized as a single token) \b - backspace\” - double quote \t - horizontal tab\0 - nul character (ASCII code 0) \\ - backslash\a - alert (speaker single beep)

  31. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types11 escape sequences in brief… Example 5A #include <stdio.h> main (void) / * function main( ) returns the value of type int by default */ { printf(“the value of constants are %c and %c\n”, ‘\x41’,’\60’); /* hexadecimal and octal escape sequences are used in printf( ) */ /* ‘\60’ can be written as ‘\060’ */ printf (“ASCII code is %d \n”,’\n’); /* ASCII code of character ‘\n’ is 10 (decimal) or A (hexadecimal) */ printf (“\” the first line of text \”\xA\” and the second” “one\”\n”); /* escape sequence \”(double quotes) is used in printf( ) */ printf (“\a1\\2\nabc\b\bde\n”); /* escape sequence used: \a (alert - short beeping from system’s speaker), \b (backspace - cursor moves one position back in the line) */ return 0; }

  32. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types12 much more on constants and types… Example 6 #include <stdio.h> int main(void) { int abc = 11100; /* 2 bytes on 16-bit computers */ printf (“multiplication 1 = %d\n”, 3*abc); printf (“multiplication 2 = %ld\n”,3*abc); printf (“multiplication 2 = %u\n”, 3*abc); printf (“multiplication 2 = %u\n”, 3u*abc); printf (“multiplication 3 = %ld\n”, 3L*abc); return 0; } PAY attention to the comment... binary representation of 33,300 (2 bytes) ?

  33. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types13 Example 7 #include <stdio.h> int main (void) { pri/* a comment */ntf (“be ready for ERROR \n”); /* ERROR:Undefined symbol pri; most probably the error message will be not the only one at the stage of compilation */ printf (“one string” “goes on here\n”); /* two string will be concatenated by compiler into single string - original C did not support it, this was a new feature in ANSI C */ printf (“result is %d”, sizeof “a”); /* string constant “a” is an array consisting of two elements */ printf (“\nthe result in the program %f\n”, 100.15*4); printf (“compare: %d and %d”, sizeof (100.15*4), sizeof (100.15f*4)); ……... }

  34. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types14 much more on constants and types… • specifier %d signals the printf( ) function to get a decimal value and output it (see the previous example ...) • for printf( ) statement it’s very important that the number of format specifiers (placeholders) corresponds exactly to the number and types of the variables in the output list, that is printf(“ ……. %_ ….. %_ …. “, , ); • C language does NOT CONTAIN I/O functions to read from the keyboard and write to the screen - standard library function printf() provides a formatted console output (the prototype of this function is given in stdio.h header file)

  35. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types15 symbolic constants and output… Example 8 #define TRUE 1 #define FALSE 0 #include<stdio.h> typedef int boolean; int main(void) { boolean a; a = TRUE; /* some other statements are included here */ printf("the value of a in different formats:\n" "%d\n%04d\n%+4d", a, a, a); return 0; } preprocessor directives TRUE and FALSE are symbolic constants; string (text) 1 is associated with a name TRUE a new name boolean is introduced for the existing typeint What is printed? 1 0001 +1 Pay attention to the presence of + sign!

  36. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types16 more on symbolic constants… • different specifiersand modifiersused in calls to the functionprintf()are covered by the examples throughout the course • example 9(see the lecture notes on the Web site)is left for self-studying Example 10 #include<stdio.h> #define TRUE 1 #define FALSE 0 int main(void) { int input_var; scanf(“%d”, &input_var); /* ….. some fragment of the program ….. */ if ((input_var == TRUE) || (input_var == FALSE)) printf(“\nthe value of input_var is %hu or %hu”, TRUE, FALSE); return 0; } what result directive #define TRUE 1 brings? don’t forget & %hu stands for short unsigned integer

  37. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types17 type conversions… • if in the expression an operator is applied to two variables of the same type, the result is quite clear; but if these variables are of different types, unexpected results can occur (the last case is prohibited by many programming languages, but in C language it’s possible) • in general, if two different types are “mixed” in the expression, the “most restrictive” type is converted to the “least restrictive” • type conversion (promotion) may bring: a) type extension b) truncation c) problems !! (this happens when conversion does not make too much sense) • type CASTING in C language: (type) expression this is discussed in the following examples

  38. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types18 type conversions… • suppose the following declaration part: char ch = ‘A’; short sv = 987; int iv; double dv; and expressions which are built on declared (defined) variables - after automatic (IMPLICIT) conversions the types of expressions are as follows: • sv - ch * 5 • dv = ch • iv = dv • iv/ch ASCII code of the character ‘A’ (uppercase) is 65 variables ch and sv are initialized type int sv and ch are automatically converted to int (integral promotion) type double type int type int (integer division takes place)

  39. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types19 more on type conversions… • Assume that the type int occupies 2 bytes (this is the case for 16-bit computers). What is printed on the screen? printf(“the first result is %u\n”, ch*sv); printf(“the second result is %d”, ch*sv); the range of int type values is [-32,768; 32,767] • the type of the arithmetic expression ch*sv is unsigned int (ch is promoted to int, sv is promoted to int as well, but the result 64155 of multiplication is too big to fit the int type range, so it is promoted to unsigned int) don’t forget this assumption ! ?

  40. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types20 explicit conversion or casting… • what happens whenCASTING(EXPLICIT conversion)is applied? (double)sv - ch * 5 (int)(dv = ch) iv = iv/(float)ch integral promotion takes place (ch is converted to int type) casting - sv is explicitly converted to double expression of the type double type int floating-point division takes place type int fractional part is lost

  41. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types21 implicit conversion & casting… Example 11 #include<stdio.h> int main(void) { char object_ch; const int object_int = 300; /* const modifier is used */ float object_f = 12.75389; unsigned object_un = 50000; object_ch = object_int; /* automatic (implicit) type conversion takes place here */ printf(“the result A is %d”, object_ch); object_ch = object_un; printf(“the result B is %d”, object_ch); object_un = object_f; printf(“\nresult C is %u”, object_un); return 0; } variable object_ch is declared of the type char… Pay attention to the way it is used in the program Explanations are given on the next slide...

  42. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types22 implicit conversion & casting… 1 byte (char type object) binary representation of the value (300) of the variable object_int 50000 (unsigned int value) schematical “explanation” of the example 11 (see the previous slide)

  43. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types23 more on conversions… • the representation of a data object is the particular pattern of bits in the memory; a conversion of a value from one type to another one may or may not involve a representation change • in INTEGRAL EXPRESSIONS only objects of types int and long (possibly, unsigned) are used char a;/* suppose some value is assigned */ long b;/* suppose some value is assigned to b as well */ …… what is the result type of the expressiona+b? (1) char type is converted to the type int (UNARY CONVERSION) (2) one operand is of the type long, the other one - int  conversion results in the longtype (BINARY CONVERSION)

  44. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types24 implicit conversion & casting… Example 12 #include<stdio.h> int main(void) { int a = 1740, b = 150; double x; char c = ‘b’; x = a/b; x = a/(b+c); x = a/(b+(double)c); x = (double)a/b; a = (int)x/4; (int)x = a/b; x = c; printf(“%d\t%d”, sizeof(c+2), sizeof((char)(c+2))); return 0; } 7.0 examples of casting 7.01613 operator sizeof returns a value of unsigned integer type which represents a size (in bytes) of its (operator’s) operand ERROR! (lvalue is expected!)

  45. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types25 some comments on the type void… • type void is a type with NO values and NO operators • its primary fields of use: (1) to show that a function DOES NOT RETURN a value (see procedures in the other programming languages) (2) to ignore a function’s return value (although it is not necessary to do): (void)printf(“something…”); function printf( ) returns a number of characterssuccessfully written to the standard output - “yes, yes, … we know this fact, but we ignore (discard) a returned value” Don’t be surprised by casting!...

  46. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types26 promotion with sign extension… Example 12A #include<stdio.h> int main(void) { char ch1 = 100; char ch2 = 200; char ch3 = ch1 + ch2; printf(“ch1 = %d\n”, ch1); printf(“ch2 = %d\n”, ch2); printf(“ch3 = %d\n”, ch3); return 0; } we assume that char is signed char when a variable of an integral type narrower than int is used in the expression, it is promoted to int (or unsigned int, if needed) conversion of ch1, ch2 and ch3 to int is done before printf( ) uses them See the next slide...

  47. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types27 promotion with sign extension… 1 byte for ch2 (200) output:ch1 =100 ch2 = -56 ch3 = 44 output:ch1 =100 ch2 = 200 ch3 = 44 Suppose the following changes are done: …….. unsigned char ch1 = 100; unsigned char ch2 = 200; unsigned char ch3 = ch1 + ch2; ……..

  48. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types28 promotion with sign extension… Why the result of printf statements look like this? Promotion still preserves the sign (all variables are unsigned)

  49. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types29 Unsignedcharacters box Borland C++ 3.1 Code Generation options in Borland C++ 3.1 and 5.0 Borland C++ 5.0

  50. Prepared by Dr.Konstantin Degtiarev, 11.02.2000 C Programming LanguageData Types30 finally, the last slide on Data Types… Example 13 #include<stdio.h> int main(void) { long double a = 300.123456789; float c; char d; printf(“1: result %.9Lf\n”, a); /* format modifier L stands for long double type */ c = a; d = a = c;/* this this the example of multiple assignment */ printf(“2: result %.9f\n”, c); printf(“3: result %c”, d); return 0; } output: 1: result 300.123456789 2: result 300.123443604 3: result , ! ?

More Related