-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.cpp
58 lines (49 loc) · 1.42 KB
/
functions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
void swap(int x, int y){ // passagem por valor
// x=10, y=20
int temp;
temp = x; // x = 10, y = 20, temp = 10;
x = y; // x = 20, y = 20, temp = 10;
y = temp; // x= 20, y = 10, temp = 10;
}
void swap2(int *x, int *y){ // passagem por endereço
// x=200, y=202
// *x = valor de a; *y = valor de b
int temp;
temp = *x; // x/*x = 200/10, y/*y = 202/20, temp = 10;
*x = *y; // *x = 20, *y = 20
*y = temp; // x= 20, y = 10, temp = 10;
}
void swap3(int &x, int &y){ // passagem por referência
// x e y são referências de a e b (respectivamente) -> 'alias' das variáveis da main
int temp;
temp = x; // x/*x = 200/10, y/*y = 202/20, temp = 10;
x = y; // *x = 20, *y = 20
y = temp; // x= 20, y = 10, temp = 10;
}
struct Rectangle {
int length;
int breadth;
};
int area(struct Rectangle &r1){ //pass by reference, creating an ALIAS for r (that from main)
return r1.length * r1.breadth;
}
void changeLenght(struct Rectangle *p, int l) {
p->length = l;
}
int main()
{
int a, b;
a = 10;
b = 20;
swap(a, b);
printf("Por valor - %d %d\n", a, b); //passagem por valor não é útil para função swap
swap2(&a, &b);
printf("Por endereço - %d %d\n", a, b);
swap3(a, b);
printf("Por referência - %d, %d\n", a, b);
struct Rectangle r={10,5};
changeLenght(&r, 20);
printf("%d", area(r));
}