Passage d'arguments par ``référence'' |
void | echange2(int* a, int* b) { |
int tmp = *a; | |
*a=*b; *b = tmp; } |
int x,y; |
echange2(&x, &y); |
void | echange3(int &a, int &b) { |
int tmp = a; | |
a=b; b = tmp; } |
int x,y; |
echange3(x, y); |
Retour d'une fonction et références |
int max(int x, int y) { return ((x>y)?x:y); } |
int a = 9, b = 19; |
max(a,b) = 16; // Erreur |
int & elt_max(int& x, int& y) { |
return ((x>y)?x:y); } |
int a = 9, b = 19; |
elt_max(a,b) = 16; // OK b == 16 |
elt_max(a,b) -= 10; // OK b == 6 |
int & elt_max_bis(int& x, int& y) { |
int z = ((x>y)?x:y); |
return z; |
} // Problèmes en perspective !!! |
Signature vs. Prototype |
int lookup(char *id, int n); |
// L'écriture suivante est également |
// possible |
int lookup(char *, int); |
Surcharge d'une fonction |
// Fonction valeur absolue |
// pour les doubles |
double abs(double d); |
// Nvelle fonction valeur absolue |
// pour les entiers |
int abs(int d); |
// Fonction arrondi pour les flottants |
float arrondi(float d); |
// Erreur : surcharge impossible |
// car la fonction arrondi a la |
// MEME signature !!! |
int arrondi(float d); |
Fonctions inline |
inline | int min(int x,int y) |
{ return (x<y?x:y); } |
#define Square(x) ((x) * (x)) |
int a = 10; |
int b = Square(a++); |
// pb!!! (a++) * (a++) |
inline int Square(int x) |
{ return x * x;} |
int c = Square(a++); // OK |