Skip to content

Commit c047ae2

Browse files
committed
Refine constplay exercise.
Fix #452.
1 parent 81a93fd commit c047ae2

File tree

2 files changed

+32
-12
lines changed

2 files changed

+32
-12
lines changed

exercises/constness/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ clean:
44
rm -f *o constplay *~ constplay.sol
55

66
constplay : constplay.cpp
7-
${CXX} -Wall -Wextra -L. -o $@ $<
7+
${CXX} -std=c++17 -Wall -Wextra -L. -o $@ $<

exercises/constness/constplay.cpp

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,25 @@
77
*/
88
void copy(int a) {
99
[[maybe_unused]] int val = a;
10-
};
10+
}
1111

1212
void copyConst(const int a) {
1313
[[maybe_unused]] int val = a;
14-
};
14+
}
1515

1616
void write(int* a) {
1717
*a = 42;
18-
};
18+
}
19+
void write(int& a) {
20+
a = 42;
21+
}
1922

20-
void read(const int *a) {
23+
void read(const int* a) {
2124
[[maybe_unused]] int val = *a;
22-
};
25+
}
26+
void read(int const & a) {
27+
[[maybe_unused]] int val = a = 2;
28+
}
2329

2430
struct Test {
2531
void hello(std::string &s) {
@@ -56,12 +62,24 @@ int main() {
5662
copyConst(m);
5763

5864
// try constant arguments of functions with pointers
59-
int *p = 0;
60-
const int *r = 0;
61-
write(p);
62-
write(r);
63-
read(p);
64-
read(r);
65+
{
66+
int *p = 0;
67+
const int *r = 0;
68+
write(p);
69+
write(r);
70+
read(p);
71+
read(r);
72+
}
73+
74+
// try constant arguments of functions with references
75+
{
76+
int p = 0;
77+
const int r = 0;
78+
write(2);
79+
write(r);
80+
read(2);
81+
read(r);
82+
}
6583

6684
// try constant method in a class
6785
Test t;
@@ -71,4 +89,6 @@ int main() {
7189
tc.hello(s);
7290
t.helloConst(s);
7391
tc.helloConst(s);
92+
93+
return 0;
7494
}

0 commit comments

Comments
 (0)