Функции Доц. д-р Владимир Димитров e-mail: [email protected] web:...

51
Функции Доц. д-р Владимир Димитров Доц. д-р Владимир Димитров e-mail: [email protected] e-mail: [email protected] Web: cht_co.tripod.com Web: cht_co.tripod.com Wap: Wap: http://www.wapdrive.com/cht_co http://www.wapdrive.com/cht_co

Post on 14-Dec-2015

224 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Функции

Доц. д-р Владимир ДимитровДоц. д-р Владимир Димитров

e-mail: [email protected]: [email protected]

Web: cht_co.tripod.comWeb: cht_co.tripod.com

Wap: http://www.wapdrive.com/cht_coWap: http://www.wapdrive.com/cht_co

Page 2: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Съдържание 1

1.1. Деклариране на Деклариране на функциифункции

1.1. Дефиниране на Дефиниране на функциифункции

2.2. Статични Статични променливипроменливи

2.2. Предаване на Предаване на аргументиаргументи

1.1. Аргументи масивиАргументи масиви

3.3. Връщане на стойностВръщане на стойност

4.4. Припокриване имената Припокриване имената на функциитена функциите

1.1. Припокриване и тип Припокриване и тип на връщаната на връщаната стойностстойност

2.2. Припокриване и Припокриване и обхватобхват

3.3. Разрешаване на Разрешаване на противоречиятапротиворечията

4.4. Разрешаване при Разрешаване при множество множество аргументиаргументи

Page 3: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Съдържание 2

5.5. Аргументи по Аргументи по умълчаванеумълчаване

6.6. Произволен брой Произволен брой аргументиаргументи

7.7. Указател към Указател към функцияфункция

5.5. МакросиМакроси

1.1. Условна Условна компилациякомпилация

6.6. СъветиСъвети

Page 4: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Деклариране на функции

Elem* next_elem() ;Elem* next_elem() ;charchar* strcpy(* strcpy(charchar* to, * to, constconst charchar* from);* from);voidvoid exit exit((iintnt););

doubledouble sqrt ( sqrt (doubledouble););doubledouble sr2 = sqrt(2); sr2 = sqrt(2);

//call sqrt() with the argument //call sqrt() with the argument doubledouble((2)2)doubledouble sq3 = sqrt("three"); sq3 = sqrt("three");

// error: sqrt() requires an argument of type // error: sqrt() requires an argument of type doubledouble

Page 5: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Дефиниране на функции 1

externextern voidvoid swap( swap(intint*, *, intint*}; // a declaration*}; // a declaration

voidvoid swap swap((intint* p, int* q)* p, int* q) // a definition// a definition

{{

intint t t = *p;= *p;

*p*p == *q;*q;

*q = t;*q = t;

}}

Page 6: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Дефиниране на функции 2

voidvoid search search((table* t, const char* key, table* t, const char* key, constconst charchar**)){{

//// no use of the third argument no use of the third argument}}

inlineinline intint fac fac((intint n) n){{

returnreturn (n<2) ? (n<2) ? 11 : n*fac(n-l); : n*fac(n-l);}}

Page 7: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Статични променливи

voidvoid f( f(intint a) a) {{whilewhile(a--) {(a--) {

staticstatic intint n = 0; n = 0; //// initialized once initialized onceintint x = 0; x = 0; //// initialized 'a' times in each call of initialized 'a' times in each call of f()f()cout cout <<<< "n == " "n == " <<<< n++ n++ <<<< " , x == " " , x == " <<<< x++ x++ <<<< '\n '; '\n ';

}}}}intint mainmain()() {{

f(3);f(3);}}

n == 0, x == 0n == 1, x == 0n == 2, x == 0

Page 8: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Предаване на аргументи 1

voidvoid f( f(intint val, val, intint& ref)& ref){{

val++;val++;ref++;ref++;

}}voidvoid g() g(){{

intint i i == 7;7;intint j = 1; j = 1;f(i,f(i,jj););

}}

Page 9: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Предаване на аргументи 2

voidvoid f( f(constconst Large Large&& arg) arg)

{{

//// the value of "arg" cannot be changed the value of "arg" cannot be changed

// // without explicit use of type conversionwithout explicit use of type conversion

}}

voidvoid g(Large& arg g(Large& arg));;

//// assume that g() modifies arg assume that g() modifies arg

Page 10: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Предаване на аргументи 3

intint strlen( strlen(constconst charchar*);*);

// number of characters in a C-style string// number of characters in a C-style string

charchar* strcpy(* strcpy(charchar* to, * to, constconst charchar* * fromfrom)); //copy a C-style string; //copy a C-style string

intint strcmp( strcmp(constconst charchar*, *, constconst charchar*);*);

// compare C-style strings// compare C-style strings

Page 11: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Предаване на аргументи 4

floatfloat fsqrt ( fsqrt (constconst floatfloat&);&);// Fortran-style sqrt taking a reference argument// Fortran-style sqrt taking a reference argument

voidvoid g ( g (doubledouble d} d}{{

floatfloat r = fsqrt (2. r = fsqrt (2.00f);f); // // pass ref pass ref to temp holding 2.to temp holding 2.00ffr = fsqrt(r);r = fsqrt(r); // // pass ref to r pass ref to rr = fsqrt(dr = fsqrt(d));; // // pass ref to temp holding pass ref to temp holding floatfloat(d)(d)

}}

Page 12: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Предаване на аргументи 5

voidvoid update( update(floatfloat& i) ;& i) ;

voidvoid g( g(doubledouble d, d, floatfloat r) r)

{{

update(2.update(2.00f);f); //// error: const argument error: const argument

update(r);update(r); //// pass ref pass ref to rto r

update(d); update(d); //// error: type conversion required error: type conversion required

}}

Page 13: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Аргументи масиви 1

intint strlen( strlen(constconst charchar*);*);

voidvoid f() f()

{{

charchar v[] = "an array"; v[] = "an array";

intint i = strlen(v); i = strlen(v);

intint j = strlen("Nicholas"); j = strlen("Nicholas");

}}

Page 14: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Аргументи масиви 2

voidvoid compute1( compute1(intint* vec_ptr, * vec_ptr, intint vec_size); vec_size); //oneway//oneway

structstruct Vec { Vec {intint* ptr;* ptr;intint size; size;

};};voidvoid compute2( compute2(constconst Vec Vec& v& v};};

// another way// another way

Page 15: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Аргументи масиви 3

charchar* day[] = {* day[] = {

"mon", "tue", "wed", "thu","mon", "tue", "wed", "thu",

"fri", "sat", "sun""fri", "sat", "sun"

};};

Page 16: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Връщане на стойност 1

intint fl() { } fl() { } // error: no value returned// error: no value returned

voidvoid f2() { } f2() { } //ok //ok

intint f3() { f3() { returnreturn 1; } 1; } // o// okk

voidvoid ff4() { 4() { returnreturn 1; } 1; }

//// error: return value in void function error: return value in void function

intint f5() { f5() { returnreturn; }; } // // error: return value missing error: return value missing

voidvoid f6() { f6() { returnreturn; }; } // // ok ok

Page 17: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Връщане на стойност 2

intint fac( fac(intint n) { n) { returnreturn (n>l (n>l)) ? ? n*fac(n-ln*fac(n-l)) : 1; } : 1; }

intint fac2 fac2((intint n) n)

{{

ifif ((n > 1) n > 1) returnreturn n*fac2(n-1) ; n*fac2(n-1) ;

returnreturn 11;;

}}

Page 18: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Връщане на стойност 3

doubledouble f f(() { ) { returnreturn 1; } 1; }// 1// 1 is implicitly converted to is implicitly converted to doubledouble(l)(l)

intint* fp() { * fp() { intint local = 1; /*...*/ local = 1; /*...*/ returnreturn &local; } &local; } //// bad bad

int&int& frfr()() { { intint local = 1; /*...*/ local = 1; /*...*/ returnreturn local; } local; } //// bad bad

Page 19: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Връщане на стойност 4

voidvoid g ( g (intint* p);* p);

voidvoid h( h(intint* p) { * p) { //* ... ** ... *// returnreturn g g((p); }p); }

//ok: return of "no value"//ok: return of "no value"

Page 20: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Припокриване имената на функциите 1

voidvoid print( print(intint);); //// print an print an intint

voidvoid print( print(constconst charchar*);*); //// print a C-style character string print a C-style character string

voidvoid print( print(doubledouble););

voidvoid print( print(longlong));;

voidvoid ff()()

{{

print(1Lprint(1L));; //// print( print(longlong))

print(1.0);print(1.0); //// print( print(ddououbleble))

print(1print(1));; //// error, ambiguous: print( error, ambiguous: print(longlong(l)) or(l)) or print(print(doubledouble(l))?(l))?

}}

Page 21: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Припокриване имената на функциите 2

voidvoid print (print (intint););voidvoid print (print (ccoonstnst charchar*};*};voidvoid print (print (doubledouble) ;) ;voidvoid print (print (longlong););voidvoid print (print (charchar););voidvoid h ( h (charchar c, c, intint i, i, shortshort s, s, floatfloat f) f) { {

print(c);print(c); // exact match: invoke print(// exact match: invoke print(charchar))print(iprint(i)); ; //// exact match: invoke print( exact match: invoke print(intint))print(s); print(s); //// integral promotion: invoke print( integral promotion: invoke print(intint))print(f); print(f); //// float to double promotion: print( float to double promotion: print(doubledouble))print('a'}; print('a'}; //// exact match: invoke print( exact match: invoke print(charchar))print(49); print(49); //// exact match: invoke print( exact match: invoke print(intint))print(0); print(0); //// exact match: invoke print( exact match: invoke print(intint))print("a"); print("a"); // exact match: invoke print(// exact match: invoke print(constconst charchar*)*)

}}

Page 22: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Припокриване имената на функциите 3

voidvoid print_int ( print_int (intint););voidvoid print_char( print_char(charchar););voidvoid print print__string(string(constconst charchar*); *); //// C-sty C-stylle stringe stringvoidvoid g ( g (intint i, i, charchar c, c, constconst charchar* p, * p, doubledouble d) d){{

print_int(i); print_int(i); //// ok okprint_char(c); print_char(c); //// ok okprint_string(p); print_string(p); //// ok okprint_int(c); print_int(c); //// ok? calls print_int( ok? calls print_int(intint(c))(c))print_char(i); print_char(i); //// ok? calls print_char( ok? calls print_char(charchar(i))(i))print_string(i); print_string(i); //error//errorprint_int(d); print_int(d); //// ok? calls print_int( ok? calls print_int(intint(d))(d))

}}

Page 23: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Припокриване и тип на стойността на връщанеfloatfloat sqrt( sqrt(floatfloat););doubledouble sqrt( sqrt(doubledouble););voidvoid f( f(doubledouble da, da, floatfloat fla) fla){{

floatfloat fl = sqrt(da); fl = sqrt(da); //// call sqrt( call sqrt(doubledouble))doubledouble d d = sqrt(da); = sqrt(da); //// call sqrt( call sqrt(doubledouble))fl = sqrt(fla); fl = sqrt(fla); // call sqrt(// call sqrt(floatfloat))d = sqrt(fla); d = sqrt(fla); //// call sqrt( call sqrt(floatfloat))

}}

Page 24: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Припокриване и обхват

voidvoid f( f(intint););

voidvoid g() g()

{{

voidvoid f( f(doubledouble););

f(l); f(l); //// call call f f((doubledouble))

}}

Page 25: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Разрешаване на противоречиятаvoidvoid fl( fl(charchar);); voidvoid fl( fl(longlong););voidvoid f f22((charchar*);*); voidvoid f2( f2(intint*);*);voidvoid k( k(intint i) i){{

ff11(i); // ambiguous: fl((i); // ambiguous: fl(charchar) or) or fl(fl(longlong))f2(0); // ambiguous: f2(f2(0); // ambiguous: f2(charchar*) or*) or f2(f2(intint*)*)

}}inlineinline voidvoid fl( fl(intint n) { fl( n) { fl(longlong (n) ); } (n) ); }f2(static_cast<f2(static_cast<intint*> (0) ) ;*> (0) ) ;

Page 26: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Разрешаване при множество аргументиintint pow( pow(intint, , intint));; doubledouble pow( pow(doubledouble, , doubledouble););complex pow(complex pow(doubledouble, complex);, complex); complex pow(complex, complex pow(complex, intint););complex pow(complex, complex pow(complex, doubledouble);); complex pow(complex, complex);complex pow(complex, complex);voidvoid k(complex z) k(complex z) {{

intint i = pow (2, i = pow (2, 2); 2); //// invoke pow( invoke pow(intint, , intint))doubledouble d = pow (2.0, d = pow (2.0, 2.0); 2.0); //// invoke pow( invoke pow(doubledouble, , doubledouble))complex z2 = pow (2,complex z2 = pow (2, z); z); //// invoke pow( invoke pow(doubledouble,, complex)complex)complex z3 = pow (z,complex z3 = pow (z, 2); 2); // invoke pow(complex,// invoke pow(complex, intint))complex z4 = pow(z,complex z4 = pow(z, z); z); //// invoke pow(complex, invoke pow(complex, complex)complex)

}}voidvoid g() g() {{

doubledouble d = pow(2.0, d = pow(2.0, 2);2);//// error: pow( error: pow(intint(2.0),(2.0), 2) or2) or pow(2.0,pow(2.0, doubledouble(2))?(2))?

}}

Page 27: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Аргументи по умълчаване 1

voidvoid print( print(intint value, value, intint base = base = 1010));; // default base is 10// default base is 10voidvoid f() f(){{

print (31);print (31); print (31, 10);print (31, 10);print (31,print (31, 16);16); print (31,print (31, 2);2);

}}31 31 31 31 11f f 1111111111

voidvoid print( print(intint value, value, intint base); base);inlineinline voidvoid print( print(intint value) { print (value, 10); } value) { print (value, 10); }

Page 28: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Аргументи по умълчаване 2

intint f( f(intint, , intint =0, =0, charchar* =0);* =0); //// ok ok

intint g( g(intint =0, =0, intint =0, =0, charchar*);*); //// errorerror

intint h( h(intint =0, =0, intint, , charchar* =0);* =0); //// error error

intint nasty( nasty(charchar*=0);*=0); // syntax error// syntax error

Page 29: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Аргументи по умълчаване 3

voidvoid f( f(intint x = 7) ; x = 7) ;voidvoid f( f(intint = 7); = 7);

//// error: cannot repeat default argument error: cannot repeat default argumentvoidvoid f( f(intint = = 8);8);

//// error: different default arguments error: different default argumentsvoidvoid g() g(){{

voidvoid f f((intint x = 9); x = 9); //// ok: this declaration hides the outer one ok: this declaration hides the outer one

//// ... ...}}

Page 30: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Произволен брой аргументи 1

intint printf( printf(constconst charchar* ...);* ...);printfprintf(("Hello, world!\n" );"Hello, world!\n" );printfprintf("("My name is %s %s\n", first _name, second _nameMy name is %s %s\n", first _name, second _name));;printfprintf((" %d + %d = %" %d + %d = %d\nd\n" ," , 2,2, 3,3, 5);5);

# include <stdio.h># include <stdio.h>intint mainmain () () {{

printf( "My name is %s %s\n", 2);printf( "My name is %s %s\n", 2);}}

intint fprint f(FILE*, fprint f(FILE*, constconst charchar* ...);* ...); //// from <cstdio> from <cstdio>intint execl( execl(constconst charchar* ...); * ...); //// from UNIX header from UNIX header

Page 31: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Произволен брой аргументи 2

externextern voidvoid error( error(intint … …));; externextern charchar* itoa (* itoa (intint, , charchar[]);[]);constconst charchar* Null* Null__cp = 0;cp = 0;intint mainmain((intint argc, argc, charchar* argv[])* argv[]) {{

switchswitch (argc (argc)) { {casecase 1: 1:

error(0, argv[0], Null_cp);error(0, argv[0], Null_cp); breakbreak;;casecase 2: 2:

error(0, argv[0], argv[error(0, argv[0], argv[11],], NullNull__cpcp));; breakbreak;;defaultdefault::

charchar buffer[8 buffer[8]];;error(1, argv[0error(1, argv[0]], "with", itoa(argc-1, buffer, "with", itoa(argc-1, buffer)), "arguments", Null_cp);, "arguments", Null_cp);

}}//// ... ...

}}

Page 32: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Произволен брой аргументи 3

voidvoid error( error(intint severity ...) severity ...)//// "severity" followed by a zero-terminated list of "severity" followed by a zero-terminated list of charchar*s*s

{{va_list ap;va_list ap;va_start(ap, severity); // arg startupva_start(ap, severity); // arg startupforfor (; ;) { (; ;) {

charchar* p = va_arg(ap, * p = va_arg(ap, charchar*);*);ifif ((p == 0) p == 0) breakbreak;;cerr cerr <<<< p p <<<< ' '; ' ';

}}va_end(apva_end(ap));; //// arg cleanup arg cleanupcerr cerr <<<< '\n '; '\n ';ifif (severity) exit(severity) ; (severity) exit(severity) ;

}}

Page 33: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 1

voidvoid error(string s) {/*...*/} error(string s) {/*...*/}

voidvoid (*efct) (string); // pointer to function (*efct) (string); // pointer to function

voidvoid f() f()

{{

efct = efct = &&error;error; //// efct points to error efct points to error

efct ("error"); efct ("error"); //// call error through efct call error through efct

}}

Page 34: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 2

voidvoid (*f (*f11) (string) = &error;) (string) = &error; //// ok ok

voidvoid (*f2) (string) = error; (*f2) (string) = error;

//// also ok; same meaning as &error also ok; same meaning as &error

voidvoid g() g()

{{

fl("Vasa");fl("Vasa"); //ok//ok

(*fl) ("Mary Rose");(*fl) ("Mary Rose"); // also ok// also ok

}}

Page 35: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 3

voidvoid (*pf) (string (*pf) (string));; // pointer to // pointer to voidvoid(string)(string)voidvoid fl fl((string);string); //// voidvoid(string)(string)intint f2(string); f2(string); //// intint(string)(string)voidvoid f3( f3(intint*);*); // // voidvoid((intint*)*)voidvoid f() f(){{

ppff == & &fl; fl; // ok// okppff = &= &ff2; 2; //// error: bad return type error: bad return typeppff = &= &ff3; 3; //// error: bad argument type error: bad argument typepfpf("("Hera"); Hera"); //// ok okpf(1); pf(1); //// error: bad argument type error: bad argument typeintint i = pf("Zeus"); i = pf("Zeus"); // error: // error: voidvoid assigned to assigned to intint

}}

Page 36: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 4

typedeftypedef voidvoid(*SIC_TYP) ((*SIC_TYP) (intint););

//// from <signal.h> from <signal.h>

typedeftypedef voidvoid(*SIG_ARG_TYP) ((*SIG_ARG_TYP) (intint););

SIGSIG__TYP signal(TYP signal(intint, SIG, SIG__ARGARG__TYP);TYP);

Page 37: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 5

typedeftypedef voidvoid(*PF) ();(*PF) ();PF edit_ops[] = { // edit operationsPF edit_ops[] = { // edit operations

&&cut, cut, &&paste, &copy, paste, &copy, &&searchsearch};};PF file_ops[] = {PF file_ops[] = { // file management// file management

&open, &open, &&append, append, &cl&close, &writeose, &write};};PF* buttonPF* button11 = edit_ops; = edit_ops;PF* button3 = file_ops;PF* button3 = file_ops;buttonbutton22[2](); [2](); // call button!'s 3rd function// call button!'s 3rd function

Page 38: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 6

typedeftypedef intint(*CFT(*CFT)) ( (constconst voidvoid*, *, ccoonstnst voidvoid*);*);voidvoid ssort ssort((voidvoid* base, size_t n, size_t sz, CFT cmp)* base, size_t n, size_t sz, CFT cmp) { {/*/* Sort the "n" elements of vector "base" into increasing orderSort the "n" elements of vector "base" into increasing order using theusing the comparison comparison function pointed to by "cmp".function pointed to by "cmp". The elements are of size "sz".The elements are of size "sz". Shell sortShell sort */ */

forfor ( (intint gap gap == n/2; 0n/2; 0 << gap; gapgap; gap /=/= 2}2} forfor { {intint i i == gap; igap; i << n; i++)n; i++) forfor ( (iintnt j j == ii -- gap; 0gap; 0 <=<= j; jj; j -=-= gap) {gap) {

charchar* b = static_cast<* b = static_cast<charchar*> (base); *> (base); //// necessary cast necessary cast charchar* pj = b* pj = b ++ jj ** sz;sz; //// &base[j] &base[j]

charchar* pjg = b* pjg = b + (j+ (j ++ gapgap)) * * sz; sz; //// &base[j+gap] &base[j+gap]ifif (cmp(pjg, (cmp(pjg, pj) <pj) < 0) { 0) { //// swap base[j] and swap base[j] and

base[j+gap]:base[j+gap]: forfor ( (intint k k == 0; k0; k << sz; k++) {sz; k++) { charchar temp = pj[k]; temp = pj[k]; pj[k] =pjg[kpj[k] =pjg[k]];; pjg[kpjg[k]] = temp; = temp; }}}}

} } }}

Page 39: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 7

structstruct User { User {charchar* name;* name;charchar* id;* id;intint dept; dept;

};};User heads[] = {User heads[] = {

"Ritchie D.M.", "Ritchie D.M.", "dmr", "dmr", 11271,11271,"Sethi R.", "Sethi R.", "ravi", "ravi", 11272,11272,"Szymanski T.G.", "Szymanski T.G.", "tgs", "tgs", 11273,11273,"Schryer N.L.", "Schryer N.L.", "n"nlls", s", 11274,11274,"Schryer N.L.", "Schryer N.L.", "n"nlls", s", 11275,11275,"Kernighan B. W.", "Kernighan B. W.", "bwk", "bwk", 1127611276

};};voidvoid print_id(User* v, print_id(User* v, intint n) n) {{

forfor ((intint i i == 0; i0; i << n; i++)n; i++)cout cout <<<< v[i].name v[i].name <<<< '\t' '\t' <<<< v[i].id v[i].id <<<< '\t' '\t' <<<< v[i].dept v[i].dept <<<< '\n' ; '\n' ;

}}

Page 40: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 8

intint cmp cmp1(1(constconst voidvoid* p, * p, constconst voidvoid* q* q))//Compare name strings//Compare name strings

{{returnreturn strcmp(static_cast< strcmp(static_cast<constconst User*> (p) User*> (p) -->> name, name,

static_cast<static_cast<constconst User*> (q) -> User*> (q) -> name);name);}}intint cmp2 cmp2((constconst voidvoid* p, * p, constconst voidvoid* q)* q)

//// Compare dept numbers Compare dept numbers{{

returnreturn static static__cascast<t<constconst User*> (p) User*> (p) ->-> dept - dept - static_cast<static_cast<constconst User*> (q) User*> (q) ->-> dept;dept;

}}

Page 41: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 9

intint main()(){{

cout cout <<<< "Heads in alphabetical order:\n"; "Heads in alphabetical order:\n";ssort(heads, 6, sizeof(Userssort(heads, 6, sizeof(User)), cmp, cmp11););print_id (heads, 6);print_id (heads, 6);cout cout <<<< "\n '; "\n ';cout cout <<<< "Heads in order of department number:\n"; "Heads in order of department number:\n";ssort (heads, 6, sizeofssort (heads, 6, sizeof((User), cmp2);User), cmp2);print_id (heads, 6);print_id (heads, 6);

}}

Page 42: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Указател към функция 10

voidvoid f f((intint););

intint f( f(charchar););

voidvoid (*pff) (*pff)((intint) = &) = &ff;; // // voidvoid f f((intint))

intint ((*pf2)(char) = &*pf2)(char) = &ff;;// // intint f(f(charchar))

voidvoid (*pf3)( (*pf3)(charchar) = ) = &&f; f; //// error: no error: no voidvoid f( f(charchar))

intint cmp3 cmp3((constconst mytype*, mytype*, constconst mytype*); mytype*);

Page 43: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Макроси 1

##definedefine NAME rest of line NAME rest of line

named = NAMEnamed = NAME

named = rest of linenamed = rest of line

##definedefine MAC(x,y MAC(x,y)) argument argument11: x argument: x argument22: y: y

expanded = MAC (foo bar, yuk yuk)expanded = MAC (foo bar, yuk yuk)

expanded = argumentexpanded = argument11: foo bar argument2: yuk yuk: foo bar argument2: yuk yuk

Page 44: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Макроси 2

##definedefine PRINT(a,b PRINT(a,b)) cout cout << << ((a)a) << << (b)(b)

##definedefine PRINT(a, b, c) cout PRINT(a, b, c) cout << << (a) (a) <<<< (b) (b) << << (c) (c)

/* trouble?: redefines, does not overload *//* trouble?: redefines, does not overload */

##definedefine FAC FAC((nn)) (n>l) ?n*FAC(n-1) : 1 (n>l) ?n*FAC(n-1) : 1

/* trouble: recursive macro *//* trouble: recursive macro */

Page 45: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Макроси 3

##definedefine CASE CASE breakbreak; ; casecase

##definedefine FOREVER FOREVER forfor (; ;) (; ;)

##definedefine PI 3.141593 PI 3.141593

##definedefine BEGIN { BEGIN {

##defmedefme END END }}

Page 46: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Макроси 4

##definedefine SQUARE(a) a*a SQUARE(a) a*a##definedefine INCR INCR__xxxx ( (xx)++xx)++

intint xx = 0; xx = 0; //// global counter global countervoidvoid f( f() ) {{

intint xx = 0; xx = 0; //// local variable local variableintint y = SQUARE (xx+2); y = SQUARE (xx+2);

//// y=xx+2*xx+2; that is y=xx+(2*xx)+2 y=xx+2*xx+2; that is y=xx+(2*xx)+2IINCR_xx;NCR_xx; //increments local xx//increments local xx

}}

Page 47: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Макроси 5

##definedefine M MIINN((a,b) ( ( (a)<(a,b) ( ( (a)<(bb) )?(a) : () )?(a) : (bb) )) )

##definedefine M2(a M2(a)) something(a something(a)) /* thoughtful /* thoughtful comment */comment */

constconst intint answer = 42; answer = 42;

templatetemplate<<classclass T> T> inlineinline T min(T a, T b) T min(T a, T b) { { returnreturn ((a<ba<b)) ? ? aa :: b; }b; }

Page 48: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Макроси 6

##definedefine NAME2 NAME2((a,b) a##ba,b) a##b

intint NAME2 NAME2((hack, cah)();hack, cah)();

intint hackcah(); hackcah();

##undefundef X X

Page 49: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Условна компилация

intint f f((intint a a

##ifdefifdef arg_two arg_two

, , intint b b

##endifendif

););

intint f( f(intint a a

););

struct Call_info {Node* arg_one;Node* arg_two;// ...

};#define arg_two x

Page 50: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Съвети 1

1.1. Бъди подозрителен към неконстантни Бъди подозрителен към неконстантни референсни аргументи; ако желаеш функцията референсни аргументи; ако желаеш функцията да изменя свойте аргументи използвай да изменя свойте аргументи използвай указатели и връщай стойностиуказатели и връщай стойности

2.2. Използвай константни референсни аргументи Използвай константни референсни аргументи когато е необходимо да минимизираш когато е необходимо да минимизираш копирането на аргументикопирането на аргументи

3.3. Използвай Използвай constconst масово и смисленомасово и смислено4.4. Избягвай макросиИзбягвай макроси5.5. Избягвай функции с произволен брой аргументиИзбягвай функции с произволен брой аргументи

Page 51: Функции Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap:

Съвети 2

6.6. Не връщай указатели или референси към локални Не връщай указатели или референси към локални променливипроменливи

7.7. Използвай припокриване на имената когато функциите Използвай припокриване на имената когато функциите извършват концептуално една и съща работа върху извършват концептуално една и съща работа върху различни типоверазлични типове

8.8. Когато припокриването става с цели числа, предоставяй Когато припокриването става с цели числа, предоставяй функции за премахване на противоречиятафункции за премахване на противоречията

9.9. Когато имаш намерение да използваш указател към Когато имаш намерение да използваш указател към функция, провери дали не можеш да приложиш функция, провери дали не можеш да приложиш виртуална функция или образецвиртуална функция или образец

10.10. Ако се налага да използваш макроси, използвай за за тях Ако се налага да използваш макроси, използвай за за тях груби имена с много и големи буквигруби имена с много и големи букви