Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refine constplay exercise. #510

Merged
merged 1 commit into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion exercises/constness/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ clean:
rm -f *o constplay *~ constplay.sol

constplay : constplay.cpp
${CXX} -Wall -Wextra -L. -o $@ $<
${CXX} -std=c++17 -Wall -Wextra -L. -o $@ $<
42 changes: 31 additions & 11 deletions exercises/constness/constplay.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,25 @@
*/
void copy(int a) {
[[maybe_unused]] int val = a;
};
}

void copyConst(const int a) {
[[maybe_unused]] int val = a;
};
}

void write(int* a) {
*a = 42;
};
}
void write(int& a) {
a = 42;
}

void read(const int *a) {
void read(const int* a) {
[[maybe_unused]] int val = *a;
};
}
void read(int const & a) {
[[maybe_unused]] int val = a = 2;
}

struct Test {
void hello(std::string &s) {
Expand Down Expand Up @@ -56,12 +62,24 @@ int main() {
copyConst(m);

// try constant arguments of functions with pointers
int *p = 0;
const int *r = 0;
write(p);
write(r);
read(p);
read(r);
{
int *p = 0;
const int *r = 0;
write(p);
write(r);
read(p);
read(r);
}

// try constant arguments of functions with references
{
int p = 0;
const int r = 0;
write(2);
write(r);
read(2);
read(r);
}

// try constant method in a class
Test t;
Expand All @@ -71,4 +89,6 @@ int main() {
tc.hello(s);
t.helloConst(s);
tc.helloConst(s);

return 0;
}