Você está na página 1de 38

Chapter 27

Chapter 27
The C Programming Language
The C Programming Language
Bjarne Stroustrup
Bjarne Stroustrup
www.stroustrup.com/Programming www.stroustrup.com/Programming
Dennis M. Ritchie
Overview
Overview

C and C++
C and C++

unction protot!pes
unction protot!pes

printf()/scanf()
printf()/scanf()

"rra!s and strings


"rra!s and strings

#emor! management
#emor! management

#acros
#acros

const
const

C/C++ interopera$i%it!
C/C++ interopera$i%it!
3 3 Stroustrup/Programming Stroustrup/Programming
C and C++
C and C++

Both were &$orn' in the Computer Science (esearch )epartment o* Both were &$orn' in the Computer Science (esearch )epartment o*
Be%% La$s in #urra! +i%%, -. Be%% La$s in #urra! +i%%, -.
4 4
dmr
ken
bwk
bs
doug

Stroustrup/Programming Stroustrup/Programming
#odern C and C++ are si$%ings
#odern C and C++ are si$%ings
Stroustrup/Programming Stroustrup/Programming 5 5
C and C++
C and C++

/n this ta%0, / use &C' to mean &/SO C12' /n this ta%0, / use &C' to mean &/SO C12'

That3s $! *ar the most common%! used de*inition o* C That3s $! *ar the most common%! used de*inition o* C

C%assic C has most%! $een rep%aced 4though ama5ing%! not comp%ete%!6 C%assic C has most%! $een rep%aced 4though ama5ing%! not comp%ete%!6

C22 is not !et wide%! used C22 is not !et wide%! used

Source compati$i%it! Source compati$i%it!

C is 4a%most6 a su$set o* C++ C is 4a%most6 a su$set o* C++

78amp%e o* e8cepion9 78amp%e o* e8cepion9 int f(int new, int class, int bool); int f(int new, int class, int bool); /: /: ok in C ok in C :/ :/

4"%most6 a%% constructs that are $oth C and C++ have the same meaning 4"%most6 a%% constructs that are $oth C and C++ have the same meaning
4semantics6 in $oth %anguages 4semantics6 in $oth %anguages

78amp%e o* e8ception9 78amp%e o* e8ception9 sizeof('a') /* sizeof('a') /* 4 in C and 1 in C++ 4 in C and 1 in C++ :/ :/

Lin0 compati$i%it! Lin0 compati$i%it!

C and C++ program *ragments can $e %in0ed together in a sing%e program C and C++ program *ragments can $e %in0ed together in a sing%e program

"nd ver! o*ten are "nd ver! o*ten are

C++ was designed to $e &as c%ose as possi$%e to C, $ut no c%oser' C++ was designed to $e &as c%ose as possi$%e to C, $ut no c%oser'

or ease o* transition or ease o* transition

or co;e8istence or co;e8istence

#ost incompati$i%ities are re%ated to C++3s stricter t!pe chec0ing #ost incompati$i%ities are re%ated to C++3s stricter t!pe chec0ing
6 6 Stroustrup/Programming Stroustrup/Programming
C and C++
C and C++

Both de*ined/contro%%ed $! /SO standards committees Both de*ined/contro%%ed $! /SO standards committees

Separate committees Separate committees

<n*ortunate%!, %eading to incompati$i%ities <n*ortunate%!, %eading to incompati$i%ities

#an! supported imp%ementations in use #an! supported imp%ementations in use

"vai%a$%e on more p%at*orms than an! other %anguages "vai%a$%e on more p%at*orms than an! other %anguages

Both primari%! aimed at and are heavi%! used *or hard s!stem Both primari%! aimed at and are heavi%! used *or hard s!stem
programming tas0s, such as programming tas0s, such as

Operating s!stems 0erne%s Operating s!stems 0erne%s

)evice drivers )evice drivers

7m$edded s!stems 7m$edded s!stems

Compi%ers Compi%ers

Communications s!stems Communications s!stems


Stroustrup/Programming Stroustrup/Programming
C and C++
C and C++

+ere we
+ere we

assume !ou 0now C++ and how to use it assume !ou 0now C++ and how to use it

descri$e the di**erences $etween C and C++ descri$e the di**erences $etween C and C++

descri$e how to program using the *aci%ities o**ered $! C descri$e how to program using the *aci%ities o**ered $! C

Our idea% o* programming and our techni=ues remain the same, $ut Our idea% o* programming and our techni=ues remain the same, $ut
the too% avai%a$%e to e8press our ideas change the too% avai%a$%e to e8press our ideas change

descri$e a *ew C &traps and pit*a%%s' descri$e a *ew C &traps and pit*a%%s'

don3t go into a%% the detai%s *rom the $oo0 don3t go into a%% the detai%s *rom the $oo0

Compati$i%it! detai%s are important, $ut rare%! interesting Compati$i%it! detai%s are important, $ut rare%! interesting
Stroustrup/Programming Stroustrup/Programming ! !
C and C++
C and C++

C++ is a genera%;purpose programming %anguage with


C++ is a genera%;purpose programming %anguage with
a $ias towards s!stems programming that
a $ias towards s!stems programming that

is a $etter C is a $etter C

supports data a$straction supports data a$straction

supports o$ject;oriented programming supports o$ject;oriented programming

supports generic programming supports generic programming


" " Stroustrup/Programming Stroustrup/Programming
C9
C9

unctions and unctions and struct structs s

#achine mode% 4$asic t!pes and operations6 #achine mode% 4$asic t!pes and operations6

Compi%ation and %in0age mode% Compi%ation and %in0age mode%


#issing in C
#issing in C
4*rom a C++ perspective6
4*rom a C++ perspective6

C%asses and mem$er *unctions C%asses and mem$er *unctions

<se <se struct struct and g%o$a% *unctions and g%o$a% *unctions

)erived c%asses and virtua% *unctions )erived c%asses and virtua% *unctions

<se <se struct struct , g%o$a% *unctions, and pointers to *unctions , g%o$a% *unctions, and pointers to *unctions

>ou can do OOP in C, $ut not c%ean%!, and wh! wou%d !ou want to? >ou can do OOP in C, $ut not c%ean%!, and wh! wou%d !ou want to?

>ou can do @P in C, $ut wh! wou%d !ou want to? >ou can do @P in C, $ut wh! wou%d !ou want to?

Temp%ates and in%ine *unctions Temp%ates and in%ine *unctions

<se macros <se macros

78ceptions 78ceptions

<se error;codes, error;return va%ues, etc. <se error;codes, error;return va%ues, etc.

unction over%oading unction over%oading

@ive each *unction a separate name @ive each *unction a separate name

new/delete new/delete

<se <se malloc()/free() malloc()/free()

(e*erences (e*erences

<se pointers <se pointers

const const in constant e8pressions in constant e8pressions

<se macros <se macros


#$ #$ Stroustrup/Programming Stroustrup/Programming
#issing in C
#issing in C
4*rom a C++ perspective6
4*rom a C++ perspective6

Aith no c%asses, temp%ates, and e8ceptions, C can3t


Aith no c%asses, temp%ates, and e8ceptions, C can3t
provide most C++ standard %i$rar! *aci%ities
provide most C++ standard %i$rar! *aci%ities

Containers Containers

vector vector, , map map, , set set, , string string, etc. , etc.

<se arra!s and pointers <se arra!s and pointers

<se macros 4rather than parameteri5ation with t!pes6 <se macros 4rather than parameteri5ation with t!pes6

STL a%gorithms STL a%gorithms

sort() sort(), , find() find(), , copy() copy(), , B B

-ot man! a%ternatives -ot man! a%ternatives

use use qsort() qsort() where !ou can where !ou can

Arite !our own, use C Arite !our own, use C


rd rd
part! %i$raries part! %i$raries

/ostreams /ostreams

<se stdio9 <se stdio9 printf() printf(), , getch() getch(), , etc. etc.

(egu%ar e8pression (egu%ar e8pression

<se a C <se a C
rd rd
part! %i$rar! part! %i$rar!
## ## Stroustrup/Programming Stroustrup/Programming
C and C++
C and C++

Lots o* use*u% code is written in C Lots o* use*u% code is written in C

Der! *ew %anguage *eatures are essentia% Der! *ew %anguage *eatures are essentia%

/n princip%e, !ou don3t need a high;%eve% %anguage, !ou cou%d write ever!thing in /n princip%e, !ou don3t need a high;%eve% %anguage, !ou cou%d write ever!thing in
assem$%er 4$ut wh! wou%d !ou want to do that?6 assem$%er 4$ut wh! wou%d !ou want to do that?6

7mu%ate high;%eve% programming techni=ues 7mu%ate high;%eve% programming techni=ues

"s direct%! supported $! C++ $ut not C "s direct%! supported $! C++ $ut not C

Arite in the C su$set o* C++ Arite in the C su$set o* C++

Compi%e in $oth %anguages to ensure consistenc! Compi%e in $oth %anguages to ensure consistenc!

<se high compi%er warning %eve%s to catch t!pe errors <se high compi%er warning %eve%s to catch t!pe errors

<se &%int' *or %arge programs <se &%int' *or %arge programs

" &%int' is a consistenc! chec0ing program " &%int' is a consistenc! chec0ing program

C and C++ are e=ua%%! e**icient C and C++ are e=ua%%! e**icient

/* !ou thin0 !ou see a di**erence, suspect di**erences in de*au%t optimi5er or %in0er /* !ou thin0 !ou see a di**erence, suspect di**erences in de*au%t optimi5er or %in0er
settings settings
Stroustrup/Programming Stroustrup/Programming #% #%
unctions
unctions

There can $e on%! one *unction o* a given name There can $e on%! one *unction o* a given name

unction argument t!pe chec0ing is optiona% unction argument t!pe chec0ing is optiona%

There are no re*erences 4and there*ore no pass;$!;re*erence6 There are no re*erences 4and there*ore no pass;$!;re*erence6

There are no mem$er *unctions There are no mem$er *unctions

There are no in%ine *unctions 4e8cept in C226 There are no in%ine *unctions 4e8cept in C226

There is an a%ternative *unction de*inition s!nta8 There is an a%ternative *unction de*inition s!nta8
Stroustrup/Programming Stroustrup/Programming #3 #3
unction protot!pes
unction protot!pes
4*unction argument chec0ing is optiona%6 4*unction argument chec0ing is optiona%6
/* /* avoid these mistakes use a compiler option that enforces C++ rules avoid these mistakes use a compiler option that enforces C++ rules */ */
int g(int); int g(int); /* /* prototype like C++ function declaration prototype like C++ function declaration */ */
int h(); int h(); /* /* not a prototype the argument types are unspecified not a prototype the argument types are unspecified */ */
int f(p,b) char* p; char b; int f(p,b) char* p; char b; /* /* old style definition not a prototype old style definition not a prototype */ */
/* /* B B */ ! */ !
int my"fct(int a, double d, char* p) int my"fct(int a, double d, char* p) /* /* new style definition a prototype new style definition a prototype */ */

f(); f(); /* /* ok by the compiler! But gives wrong/unepected results ok by the compiler! But gives wrong/unepected results */ */
f(d,p); f(d,p); /* /* ok by the compiler! But gives wrong/unepected results ok by the compiler! But gives wrong/unepected results */ */
h(d); h(d); /* /* ok by the compiler! But may give wrong/unepected results ok by the compiler! But may give wrong/unepected results */ */
ff(d); ff(d); /* /* ok by the compiler! But may give wrong/unepected results ok by the compiler! But may give wrong/unepected results */ */
g(p); g(p); /* /* error! wrong type error! wrong type */ */
g(); g(); /* /* error! argument missing error! argument missing */ */
! !
#4 #4 Stroustrup/Programming Stroustrup/Programming
printf()
printf()
E man! peop%e3s *avorite C *unction
E man! peop%e3s *avorite C *unction
/* /* no iostreams use stdio no iostreams use stdio */ */
#include$stdio%h& #include$stdio%h& /* /* defines defines int printf(const char* format, ); int printf(const char* format, ); */ */
int main(void) int main(void)

printf('(ello, world)n'); printf('(ello, world)n');
return *; return *;
! !
void f(double d, char* s, int i, char ch) void f(double d, char* s, int i, char ch)

printf('double +g string +s int +i char +c)n', d, s, i, ch); printf('double +g string +s int +i char +c)n', d, s, i, ch);
printf('goof +s)n', i); printf('goof +s)n', i); /* /* uncaught error uncaught error */ */
! !
#5 #5
&ormat strings
&ormatting characters
'rguments to be (ormatted
&ormat string
Stroustrup/Programming Stroustrup/Programming
scanf()
scanf()
and *riends
and *riends
/* /* the most popular input functions from the most popular input functions from <stdio.h> <stdio.h>! ! :/ :/
int i , getchar(); int i , getchar(); /* /* note note int int" not " not char char# #
getchar() getchar() returns returns EOF EOF when it reaches end of file when it reaches end of file :/ :/
p , gets(); p , gets(); /* /* read $ read $\n \n$ $ terminated line into terminated line into char char array pointed to by array pointed to by p p */ */
void f(int* pi, char* pc, double* pd, char* ps) void f(int* pi, char* pc, double* pd, char* ps)
/* /* read into variables whose addresses are passed as pointers! read into variables whose addresses are passed as pointers! :/ :/
scanf('+i +c +g +s', pi, pc, pd, ps); scanf('+i +c +g +s', pi, pc, pd, ps);
/* /* %s %s skips initial whitespace and is terminated by whitespace skips initial whitespace and is terminated by whitespace :/ :/
F F
int i; char c; double d; char s-.**/; f(0i, 0c, 0d, s); /* int i; char c; double d; char s-.**/; f(0i, 0c, 0d, s); /* call to assign to call to assign to i i" " c c" " d d" and " and s s :/ :/

)on3t )on3t ever ever use use gets() gets() or or scanf('+s') scanf('+s')G G

Consider them poisoned Consider them poisoned

The! are the source o* The! are the source o* many many securit! vio%ations securit! vio%ations

"n over*%ow is easi%! arranged and easi%! e8p%oita$%e "n over*%ow is easi%! arranged and easi%! e8p%oita$%e

<se <se getchar() getchar()


#6 #6 Stroustrup/Programming Stroustrup/Programming
printf()
printf()
and
and
scanf()
scanf()
are not t!pe sa*e
are not t!pe sa*e
double d , *; double d , *;
int s , *; int s , *;
printf('d1 +d , s1 +s)n', d, s); printf('d1 +d , s1 +s)n', d, s); /* /* compiles and runs compiles and runs
the result might surprise you the result might surprise you :/ :/
# #
)d* (or )decima+*, not )doub+e*
)s* (or )string*
Stroustrup/Programming Stroustrup/Programming

Though error;prone, Though error;prone, printf() printf() is convenient *or $ui%t;in t!pes is convenient *or $ui%t;in t!pes

printf() printf() *ormats are not e8tensi$%e to user;de*ined t!pes *ormats are not e8tensi$%e to user;de*ined t!pes

7.g. no 7.g. no +2 +2 *or *or 2y"type 2y"type va%ues va%ues

Beware9 a Beware9 a printf () printf () with a user;supp%ied *ormat string is a crac0er too% with a user;supp%ied *ormat string is a crac0er too%
"rra!s and pointers
"rra!s and pointers

)e*ined a%most e8act%! as in C++ )e*ined a%most e8act%! as in C++

/n C, !ou have to use them essentia%%! a%% the time /n C, !ou have to use them essentia%%! a%% the time

$ecause there is no $ecause there is no vector, map, string vector, map, string, etc. , etc.

(emem$er
(emem$er

"n arra! doesn3t 0now how %ong it is "n arra! doesn3t 0now how %ong it is

There is no arra! assignment There is no arra! assignment

use use memcpy() memcpy()

" C;st!%e string is a 5ero;terminated arra! " C;st!%e string is a 5ero;terminated arra!
#! #! Stroustrup/Programming Stroustrup/Programming
C;st!%e strings
C;st!%e strings

/n C a string 4ca%%ed a C;string or a C;st!%e string in C++ /n C a string 4ca%%ed a C;string or a C;st!%e string in C++
%iterature6 is a 5ero;terminated arra! o* characters %iterature6 is a 5ero;terminated arra! o* characters
char* p , 'asdf'; char* p , 'asdf';
char s- / , 'asdf'; char s- / , 'asdf';
#" #"
-a- -s- -(- -d- $
p.
-a- -s- -(- -d- $
s.
Stroustrup/Programming Stroustrup/Programming
C;st!%e strings
C;st!%e strings

Comparing strings
Comparing strings
#include $string%h& #include $string%h&
if (s. , , s3) if (s. , , s3) /: /: do do s s and and s! s! point to the same array% point to the same array%
&typically not what you want' &typically not what you want' :/ :/
! !
if (strcmp(s.,s3) , , *) if (strcmp(s.,s3) , , *) /: /: do do s s and and s! s! hold the same characters% hold the same characters% :/ :/
! !

inding the %engths o* a string


inding the %engths o* a string
int lgt , strlen(s); int lgt , strlen(s); /* /* note! goes through the string at run time note! goes through the string at run time
looking for the terminating ( looking for the terminating ( */ */

Cop!ing strings
Cop!ing strings
strcpy(s.,s3); strcpy(s.,s3); /* /* copy characters from copy characters from s! s! into into s s
be sure that be sure that s s can hold that many characters can hold that many characters :/ :/
%$ %$ Stroustrup/Programming Stroustrup/Programming
C;st!%e strings
C;st!%e strings

The string cop! *unction


The string cop! *unction
strcpy()
strcpy()
is the archet!pica% C
is the archet!pica% C
*unction 4*ound in the /SO C standard %i$rar!6
*unction 4*ound in the /SO C standard %i$rar!6

<n%ess !ou understand the imp%ementation $e%ow, don3t


<n%ess !ou understand the imp%ementation $e%ow, don3t
c%aim to understand C9
c%aim to understand C9
char* strcpy(char *p, const char *q) char* strcpy(char *p, const char *q)

while (*p44 , *q44); while (*p44 , *q44);
return p; return p;
! !

or an e8p%anation see *or e8amp%e HI( or TC++PL


or an e8p%anation see *or e8amp%e HI( or TC++PL
Stroustrup/Programming Stroustrup/Programming %# %#
Standard *unction %i$raries
Standard *unction %i$raries

$stdio%h& $stdio%h& printf() printf(), , scanf() scanf(), etc. , etc.

$string%h& $string%h& strcmp() strcmp(), etc. , etc.

$ctype%c& $ctype%c& isspace() isspace(), , etc. etc.

$stdlib%h& $stdlib%h& malloc() malloc(), , etc. etc.

$math%h& $math%h& sqrt() sqrt(), , etc. etc.

Aarning9 B! de*au%t, #icroso*t tries to *orce !ou to use sa*er, Aarning9 B! de*au%t, #icroso*t tries to *orce !ou to use sa*er,
$ut non;standard, a%ternatives to the unsa*e C standard %i$rar! $ut non;standard, a%ternatives to the unsa*e C standard %i$rar!
*unctions *unctions
%% %% Stroustrup/Programming Stroustrup/Programming
ree store9 ma%%oc46/*ree46
ree store9 ma%%oc46/*ree46
#include$stdlib%h& #include$stdlib%h&
void f(int n) void f(int n)
/* /* ma""oc() ma""oc() takes a number of bytes as its argument takes a number of bytes as its argument */ */
int* p , (int*)malloc(sizeof(int)*n); int* p , (int*)malloc(sizeof(int)*n); /* /* allocate an array of allocate an array of n int n ints s :/ :/
/* /* B B */ */
free(p); free(p); /* /* free() free() returns memory allocated by returns memory allocated by ma""oc() ma""oc() to free store to free store :/ :/
! !
%3 %3 Stroustrup/Programming Stroustrup/Programming
ree store9 ma%%oc46/*ree46
ree store9 ma%%oc46/*ree46

Litt%e compi%e;time chec0ing


Litt%e compi%e;time chec0ing
/* /* ma""oc() ma""oc() returns a returns a void*. void*. )ou can leave out the cast of malloc&'" but don*t )ou can leave out the cast of malloc&'" but don*t */ */
double* p , malloc(sizeof(int)*n); double* p , malloc(sizeof(int)*n); /* /* probably a bug probably a bug */ */

Litt%e run;time chec0ing


Litt%e run;time chec0ing
int* q , malloc(sizeof(int)*m); /* int* q , malloc(sizeof(int)*m); /* m int m ints s */ */
for (int i,*; i$n; 44i) init(q-i/); for (int i,*; i$n; 44i) init(q-i/);

-o initia%i5ation/c%eanup
-o initia%i5ation/c%eanup

malloc() malloc() doesn3t ca%% constructors doesn3t ca%% constructors

free() free() doesn3t ca%% destructors doesn3t ca%% destructors

Arite and remem$er to use !our own Arite and remem$er to use !our own init() init() and and cleanup() cleanup()

There is no wa! to ensure automatic c%eanup


There is no wa! to ensure automatic c%eanup

)on3t use
)on3t use
malloc()/free()
malloc()/free()
in C++ programs
in C++ programs

new/delete new/delete are as *ast and a%most a%wa!s $etter are as *ast and a%most a%wa!s $etter
%4 %4 Stroustrup/Programming Stroustrup/Programming
<ncast
<ncast
malloc()
malloc()

The major C/C++ incompati$i%it! in rea%;wor%d code The major C/C++ incompati$i%it! in rea%;wor%d code

-ot;t!pe sa*e -ot;t!pe sa*e

+istorica%%! a pre;standard C compati$i%it! hac0/*eature +istorica%%! a pre;standard C compati$i%it! hac0/*eature

"%wa!s controversia% "%wa!s controversia%

<nnecessari%! so /#O <nnecessari%! so /#O


void* alloc(size"t 5); void* alloc(size"t 5); /* /* allocate bytes allocate bytes
in C" but not in C++" in C" but not in C++" void* void* converts to any converts to any #* #* */ */
void f (int n) void f (int n)

int* p , alloc(n*sizeof(int)); int* p , alloc(n*sizeof(int)); /* /* ok in C# error in C++ ok in C# error in C++ */ */
int* q , (int*)alloc(n*sizeof(int)); int* q , (int*)alloc(n*sizeof(int)); /* /* ok in C and C++ ok in C and C++ */ */
/* /* B :/ B :/
! !
Stroustrup/Programming Stroustrup/Programming %5 %5
void:
void:

Ah! does void: convert to T: in C $ut not in C++? Ah! does void: convert to T: in C $ut not in C++?

C needs it to save !ou *rom casting the resu%t o* C needs it to save !ou *rom casting the resu%t o* malloc() malloc()

C++ does not9 use C++ does not9 use new new

Ah! is a Ah! is a void* void* to to 6* 6* conversion not t!pe sa*e? conversion not t!pe sa*e?
void f() void f()

char i , *; char i , *;
char 7 , *; char 7 , *;
char* p , 0i; char* p , 0i;
void* q , p; void* q , p;
int* pp , q; int* pp , q; /* /* unsafe" legal C# error in C++ unsafe" legal C# error in C++ */ */
*pp , 8.; *pp , 8.; /* /* overwrite memory starting at +i overwrite memory starting at +i */ */
! !
Stroustrup/Programming Stroustrup/Programming %6 %6
Comments
Comments

// // comments were introduced $! Bjarne Stroustrup into C++ comments were introduced $! Bjarne Stroustrup into C++
*rom C3s ancestor BCPL when he got rea%%! *ed up with t!ping *rom C3s ancestor BCPL when he got rea%%! *ed up with t!ping
/* /* B B */ */ comments comments

// // comments are accepted $! most C dia%ects inc%uding the new comments are accepted $! most C dia%ects inc%uding the new
/SO standard C 4C226 /SO standard C 4C226
% % Stroustrup/Programming Stroustrup/Programming
const
const
// // in C" a in C" a const const is never a compile time constant is never a compile time constant
const int ma5 , 9*; const int ma5 , 9*;
const int 5; const int 5; // // const const not initiali,ed! ok in C &error in C++' not initiali,ed! ok in C &error in C++'
void f(int v) void f(int v)

int a.-ma5/; int a.-ma5/; // // error! array bound not a constant & error! array bound not a constant &ma$ ma$ is not a constant!' is not a constant!'
int a3-5/; int a3-5/; // // error! array bound not a constant error! array bound not a constant ( (here you see why' here you see why'
switch (v) switch (v)
case .1 case .1
// // - -
case ma51 case ma51 // // error! case label not a constant error! case label not a constant
// // - -
! !
! !
%! %! Stroustrup/Programming Stroustrup/Programming
/nstead o*
/nstead o*
const
const
use macros
use macros
#define ma5 9* #define ma5 9*
void f(int v) void f(int v)

int a.-ma5/; int a.-ma5/; // // ok ok
switch (v) switch (v)
case .1 case .1
// // - -
case ma51 case ma51 // // ok ok
// // - -
! !
! !
%" %" Stroustrup/Programming Stroustrup/Programming
Beware o* macros
Beware o* macros
#include 'my"header%h' #include 'my"header%h'
// // - -
int ma5(int a, int b) return a&,b:a1b; ! int ma5(int a, int b) return a&,b:a1b; ! // // error! .obscure error message/ error! .obscure error message/

"s it happened "s it happened my"header%h my"header%h contained the macro contained the macro ma5 ma5 *rom the previous *rom the previous
s%ide so what the compi%er saw was s%ide so what the compi%er saw was
int 9*(int a, int b) return a&,b:a1b; ! int 9*(int a, int b) return a&,b:a1b; !

-o wonder it comp%ainedG -o wonder it comp%ainedG

There are tens o* thousands o* macros in popu%ar header *i%es. There are tens o* thousands o* macros in popu%ar header *i%es.

"%wa!s de*ine macros with "%wa!s de*ine macros with ;<<"=;>? ;<<"=;>? names, e.g. names, e.g.
#define 2@"2;A 9* #define 2@"2;A 9*
and never give an!thing $ut a macro an and never give an!thing $ut a macro an ;<<"=;>? ;<<"=;>? name name

<n*ortunate%!, not ever!one o$e!s the "LLJC"PS convention <n*ortunate%!, not ever!one o$e!s the "LLJC"PS convention
3$ 3$ Stroustrup/Programming Stroustrup/Programming
C/C++ interopera$i%it!
C/C++ interopera$i%it!

Aor0s $ecause o* shared %in0age mode%


Aor0s $ecause o* shared %in0age mode%

Aor0s $ecause a shared mode% *or simp%e o$jects


Aor0s $ecause a shared mode% *or simp%e o$jects

$ui%t;in t!pes and structs/c%asses $ui%t;in t!pes and structs/c%asses

Optima%/7**icient
Optima%/7**icient

-o $ehind;the;scenes re*ormatting/conversions -o $ehind;the;scenes re*ormatting/conversions


Stroustrup/Programming Stroustrup/Programming 3# 3#
Ca%%ing C *rom C++
Ca%%ing C *rom C++

<se <se e5tern '=' e5tern '=' to te%% the C++ compi%er to use C ca%%ing to te%% the C++ compi%er to use C ca%%ing
conventions conventions
// // calling C function from C++! calling C function from C++!

e5tern '=' double sqrt(double); e5tern '=' double sqrt(double); // // link as a C function link as a C function

void my"c"plus"plus"fct() void my"c"plus"plus"fct()

double sr , sqrt(3); double sr , sqrt(3);
// // - -
! !
Stroustrup/Programming Stroustrup/Programming 3% 3%
Ca%%ing C++ *rom C
Ca%%ing C++ *rom C

-o specia% action is needed *rom the C compi%er -o specia% action is needed *rom the C compi%er
/: /: call C++ function from C! call C++ function from C! :/ :/

int call"f(?* p, int i); int call"f(?* p, int i); /0 call f for ob1ect pointed to by p with argument i /0 call f for ob1ect pointed to by p with argument i */ */
struct ?* maBe"?(int 5, const char* p); /* struct ?* maBe"?(int 5, const char* p); /* make 2& "p' on the free store make 2& "p' on the free store */ */

void my"c"fct(int i) void my"c"fct(int i)

/* /* - - */ */
struct ?* p , maBe"?(.C, 'foo'); struct ?* p , maBe"?(.C, 'foo');
int 5 , call"f(p,i); int 5 , call"f(p,i);
/* /* - - */ */
! !
Stroustrup/Programming Stroustrup/Programming 33 33
Aord counting e8amp%e
Aord counting e8amp%e
4C++ version6
4C++ version6
#include$map& #include$map&
#include$string& #include$string&
#include$iostream& #include$iostream&
using namespace std; using namespace std;
int main() int main()

map$string,int& m; map$string,int& m;
string s; string s;
while (cin&&s) m-s/44; while (cin&&s) m-s/44; // // use use get"ine() get"ine() if you really want lines if you really want lines
for(map$string,int&11iterator p , m%begin(); pD,m%end(); 44p) for(map$string,int&11iterator p , m%begin(); pD,m%end(); 44p)
cout $$ p8&first $$ ' 1 ' $$ p8&second $$ ')n'; cout $$ p8&first $$ ' 1 ' $$ p8&second $$ ')n';
! !
34 34 Stroustrup/Programming Stroustrup/Programming
Aord counting e8amp%e
Aord counting e8amp%e
4C version6
4C version6
// // word3fre45c word3fre45c
// // 6alter C5 7augherity 6alter C5 7augherity
#include $stdio%h& #include $stdio%h&
#include $stdlib%h& #include $stdlib%h&
#include $string%h& #include $string%h&
#define 2;A"EFGH? .*** /* #define 2;A"EFGH? .*** /* ma uni4ue words to count ma uni4ue words to count */ */
#define 2;A"EFGH"<IJK6( .** #define 2;A"EFGH"<IJK6( .**
#define ?6G(s) #s #define ?6G(s) #s /* /* macros for scanf format macros for scanf format */ */
#define A?6G(s) ?6G(s) #define A?6G(s) ?6G(s)
typedef struct record typedef struct record
char word-2;A"EFGH"<IJK6( 4 ./; char word-2;A"EFGH"<IJK6( 4 ./;
int count; int count;
! record; ! record;
35 35 Stroustrup/Programming Stroustrup/Programming
Aord counting e8amp%e
Aord counting e8amp%e
4C version6
4C version6
int main() int main()

// // - read words and build table - - read words and build table -
qsort(table, num"words, sizeof(record), strcmp); qsort(table, num"words, sizeof(record), strcmp);
for(iter,*; iter$num"words; 44iter) for(iter,*; iter$num"words; 44iter)
printf('+s +d)n',table-iter/%word,table-iter/%count); printf('+s +d)n',table-iter/%word,table-iter/%count);
return IAL6"?M==I??; return IAL6"?M==I??;
! !
36 36 Stroustrup/Programming Stroustrup/Programming
Aord counting e8amp%e
Aord counting e8amp%e
4most o* main6
4most o* main6
record table-2;A"EFGH? 4 ./; record table-2;A"EFGH? 4 ./;
int num"words , *; int num"words , *;
char word-2;A"EFGH"<IJK6( 4 ./; char word-2;A"EFGH"<IJK6( 4 ./;
int iter; int iter;
while(scanf('+' A?6G(2;A"EFGH"<IJK6() 's', word) D, IFN) while(scanf('+' A?6G(2;A"EFGH"<IJK6() 's', word) D, IFN)
for(iter , *; iter $ num"words 00 strcmp(table-iter/%word, word); 44iter); for(iter , *; iter $ num"words 00 strcmp(table-iter/%word, word); 44iter);
if(iter ,, num"words) if(iter ,, num"words)
strncpy(table-num"words/%word, word, 2;A"EFGH"<IJK6( 4 .); strncpy(table-num"words/%word, word, 2;A"EFGH"<IJK6( 4 .);
table-num"words44/%count , .; table-num"words44/%count , .;
! !
else table-iter/%count44; else table-iter/%count44;
if(num"words & 2;A"EFGH?) if(num"words & 2;A"EFGH?)
printf('table is full)n'); printf('table is full)n');
return IAL6"N;L<MGI; return IAL6"N;L<MGI;
! !
! !
3 3 Stroustrup/Programming Stroustrup/Programming
Aord counting e8amp%e
Aord counting e8amp%e
4C version6
4C version6

Comments Comments

/n 4some6 co%%o=uia% C st!%e 4not written $! BS6 /n 4some6 co%%o=uia% C st!%e 4not written $! BS6

/t3s so %ong and comp%icatedG 4m! *irst reaction E BS6 /t3s so %ong and comp%icatedG 4m! *irst reaction E BS6

See, !ou don3t need an! *anc! and comp%icated %anguage *eaturesGGG 4not m! See, !ou don3t need an! *anc! and comp%icated %anguage *eaturesGGG 4not m!
comment E BS6 comment E BS6

/#+O not a ver! good pro$%em *or using C /#+O not a ver! good pro$%em *or using C

-ot an at!pica% app%ication, $ut not %ow;%eve% s!stems programming -ot an at!pica% app%ication, $ut not %ow;%eve% s!stems programming

/t3s a%so C++ e8cept that in C++, the argument to /t3s a%so C++ e8cept that in C++, the argument to qsort() qsort() shou%d $e cast to its shou%d $e cast to its
proper t!pe9 proper t!pe9

(int (*)(const void*, const void*))strcmp (int (*)(const void*, const void*))strcmp

Ahat are those macros doing? Ahat are those macros doing?

#a8es out at #a8es out at 2;A"EFGH 2;A"EFGH words words

)oesn3t hand%e words %onger than )oesn3t hand%e words %onger than 2;A"EFGH"<IJK6( 2;A"EFGH"<IJK6(

irst reads and then sorts irst reads and then sorts

/nherent%! s%ower than the co%%o=uia% C++ version 4which uses a /nherent%! s%ower than the co%%o=uia% C++ version 4which uses a map map6 6
Stroustrup/Programming Stroustrup/Programming 3! 3!
#ore in*ormation
#ore in*ormation

Hernighan I (itchie9 The C Programming Language Hernighan I (itchie9 The C Programming Language

The c%assic The c%assic

Stroustrup9 TC++PL, "ppendi8 B9 Compati$i%it! Stroustrup9 TC++PL, "ppendi8 B9 Compati$i%it!

C/C++ incompati$i%ities, on m! home pages C/C++ incompati$i%ities, on m! home pages

Stroustrup9 Learning Standard C++ as a -ew Language. Stroustrup9 Learning Standard C++ as a -ew Language.

St!%e and techni=ue comparisons St!%e and techni=ue comparisons

www.research.att.com/K$s/newJ%earning.pd* www.research.att.com/K$s/newJ%earning.pd*

Lots o* $oo0 reviews9 www.accu.org Lots o* $oo0 reviews9 www.accu.org


3" 3" Stroustrup/Programming Stroustrup/Programming

Você também pode gostar