c 程式語言 learn how to write c programs data types program structures input/output and...
TRANSCRIPT
C 程式語言 Learn how to write C programs
Data Types
Program Structures
Input/Output and Files
Preprocessing
Compile Link Execute (Visual C++ 6.0)
C Programming Language Introduction 1
Information about the courseInformation 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/
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 2
General informationGeneral 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 abstraction which expresses the steps of specification in the form which is converted by translator into set of computer instructions
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 3
Programming languages Programming languages
studying. What are the aims?studying. What are the aims?
to understand better 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 languagesClassification of languages imperative languages (e.g. Pascal, C/C++, Fortran) non-imperative languages (e.g. Prolog, LISP)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 4
Translation process and its main stages Translation process and its main stages
(all stages are machine-dependent)(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)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 5
Compilation, linking & loadingCompilation, 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
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 6
Compilation, linking & loadingCompilation, 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
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 7
Language portabilityLanguage 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)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 8
Brief comments on C++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)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 9
Brief comments on C++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 CC++++ 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
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 10
Brief comments on C++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: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...Now we start with C language...
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 11
Origins of C languageOrigins 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)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Introduction 12
C language keywordsC 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!
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language First examples 1
Example 1Example 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; }
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language First examples 2
#include<stdio.h> Example 1AExample 1A int main(void) { printf(“the first output line.”); printf(“the second output line”); return 0; }
#include<stdio.h> Example 2Example 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; }
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language First examples 3
printf(“the value is %d\n”, my_variable);
#include<stdio.h> Example 3Example 3 main(void) { int i = 0; while(++i <= 9) { if(i == 5) continue; printf(“the result is %d”,i); } return 0; }
list of variables formatspecifier
control string
PAYattention !
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language First examples 4
Example 3AExample 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; }
1 4 9 16 25 36 49 64 81 1000 1 2 3 4 5 6 7 8 9
array sqrs[ ] consists of 10 elements
indices start with 0 !
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language First examples 5
#include<stdio.h> Example 4Example 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; }
PAYattention !
result::
_T_e_s_t_ _s_t_r_i_n_g_._._._
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language First examples 6
Example 4AExample 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 prototypeprovides the C
compiler with a necessary information
about the function
PAY attention ! (absence of semicolon)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Explanations 1
Functions are central to C/C++ programmingFunctions 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
Functions
Library functions
(purchased as a part of the C compiler package or from the
other vendors)
User-defined functions
(created by a programmer)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 1
Concept of data types determines …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
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 2
Some useful remainders on types...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 unsigned
int sizeof(float) sizeof(double)
before a variable is used in a C program, it must be declared:typename variable_name;
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 3
typedef and constants...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.12315. -7.139
floating-point constants can be written in scientific notation as well (1.12e-3 0.00112)
literal floating-point constants are treatedby C compiler as a double-precision numbers
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 4
more on constants…more on constants…
a literal constant written without decimal point is represented by the compiler as an integer constant:
-11153+638
043
0x840X137
const long tum = 12345678;
decimal integer constants
octal (base 8) integer constant startwith a leading zero (0)
hexadecimal (base 16) integer constantsstart with a leading 0x or 0X
tum is a symbolic constant
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 5
more on constants and types…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:
135135U (135u)135UL (135ul)135.17135.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 unsigned int
constant of the type float?
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 6
more on constants and types…more on constants and types…
Example 4AExample 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:result: the first result is 3.97569723690 the second result is 3.97569705882
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 7
more and more on constants and types…more and more on constants and types…
Example 5Example 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 (poundsign) # in format specifiers
result:
1. result: 150 264 2. result: 150 3. result: 0xd 015 4. result: 0XA
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 8
even more on constants and types…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 var2
are of the type enum game and their possible values are listed as enumerators (see the list in curly brackets)
each enumerator internally is represented as an integer constant value (by default, socker 0, cricket 1, … etc.)
list of enumeratorslist of enumerators list of variableslist of variableskeyword tag
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 9
much more on constants and types…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)
stands for 11 (the previous value +1)
requiresstdio.h header
file
values 0 and -5appear in the
output
something verystrange (garbage)
in the output ...
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 10
much more on constants and types…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)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 11
escape sequences in brief…escape sequences in brief…
Example 5AExample 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; }
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 12
much more on constants and types…much more on constants and types…
Example 6Example 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...PAY attention to the comment...
binary representation
of 33,300 (2 bytes)
1 0 0 0 0 0 0 0 1 1 1 0 1 0 0 015 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
?
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 13
Example 7Example 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)); ……...
}
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 14
much more on constants and types…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)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 15
symbolic constants and output…symbolic constants and output… Example 8Example 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 type int
Pay attention to the presence of + sign!
What is printed?
10001 +1
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 16
more on symbolic constants…more on symbolic constants…
different specifiers and modifiers used in calls to the function printf() are covered by the examples throughout the course
example 9 (see the lecture notes on the Web site) is left for self-studying
Example 10Example 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
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 17
type conversions…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 extensionb) truncationc) 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
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 18
type conversions…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 65variables chand sv areinitialized
type int
type doubletype int
type int (integerdivision takes
place)
sv and ch areautomaticallyconverted toint (integral promotion)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 19
more on type conversions…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 forgetthis
assumption !
1 1 1 1 1 0 1 0 1 0 0 1 1 0 1 115 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
?
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 20
explicit conversion or casting…explicit conversion or casting…
what happens when CASTING (EXPLICIT conversion) is applied?
(double)sv - ch * 5
(int)(dv = ch)
iv = iv/(float)ch
integral promotiontakes place (ch is
converted to int type)
casting - sv isexplicitly
converted todouble
expression of the type double
floating-point division takes place
type int
type int
fractional part is lost
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 21
implicit conversion & casting…implicit conversion & casting… Example 11Example 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...
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
implicit conversion & casting…implicit conversion & casting…
C Programming Language Data Types 22
binary representation of the value (300) of the variable object_int
0 0 0 0 0 0 0 1 0 0 1 0 1 1 0 015 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 1 0 0 0 0 1 1 0 1 0 1 0 0 0 015 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
50000(unsignedint value)
1 byte(char type object)
schematical “explanation” of the example 11 (see the previous slide)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 23
more on conversions…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 expression a+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 long type (BINARY CONVERSION)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 24
implicit conversion & casting…implicit conversion & casting… Example 12Example 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; }
operator sizeof returns a value of unsigned integer type which
represents a size (in bytes) of its (operator’s) operand
examples of casting
7.0
7.01613
ERROR!(lvalue is
expected!)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 25
some comments on the type void…some comments on the type void…
type void is a type with NONO values and NONO 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 characters successfully written to the standard output - “yes, yes, … we know this fact, but we ignore (discard) a returned value”
Don’t be surprised by casting!...
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 26
promotion with promotion with signsign extension… extension… Example 12AExample 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 themSee the next slide...
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 27
1 1 1 1 1 1 1 1 1 1 0 0 1 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 byte for ch2 (200)
promotion with promotion with signsign extension… extension…
output: ch1 = 100 ch2 = -56 ch3 = 44
Suppose the following changes are done:
…….. unsigned char ch1 = 100; unsigned char ch2 = 200; unsigned char ch3 = ch1 + ch2; ……..
output: ch1 = 100 ch2 = 200 ch3 = 44
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 28
promotion with promotion with signsign extension… extension…
Why the result of printf statements look like this?
0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Promotion still preserves
the sign (all variablesare unsigned)
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 29
Code Generation
options in Borland C++ 3.1 and 5.0
Unsigned characters
box
Borland C++ 5.0
Borland C++ 3.1
Prepared by Dr.Konstantin Degtiarev, 11.02.2000
C Programming Language Data Types 30
finally, the last slide on Data Types…finally, the last slide on Data Types… Example 13Example 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.1234567892: result 300.1234436043: result ,
?
!
Prepared by Dr.Konstantin Degtiarev, 11.02.2000