I'm fairly new when it comes to C++ so bear with me. When learning about return values in functions, I was told that the proper way to write pure functions is to return a value every time. I attempted this in a small function that checks the user's age and returns whether or not they're an adult. The issue here, at least for me, is understanding the proper utilization of these return values. For example, in this code snippet here I'm returning whether or not they are an adult given their age in years.
main.h
#pragma once
#define LOG(x) std::cout << x
#define LOGCIN(x) std::cin >> x
bool check_age(int age) {
if (age >= 18)
return true;
else
return false;
}
main.cpp
#include <iostream>
#include "main.h"
bool check_age(int age);
int main() {
int age;
LOG("Enter your current age in years: ");
LOGCIN(age);
bool adult = check_age(age);
if (adult == true) {
LOG("You are an adult!");
} else {
LOG("You are not an adult!");
}
}
However, when I rewrote this code without using return values, I got this.
main.h
#pragma once
#define LOG(x) std::cout << x
#define LOGCIN(x) std::cin >> x
void check_age(int age) {
if (age >= 18)
LOG("You are an adult!");
else
LOG("You are not an adult!");
}
main.cpp
#include <iostream>
#include "main.h"
void check_age(int age);
int main() {
int age;
LOG("Enter your current age in years: ");
LOGCIN(age);
check_age(age);
}
As you can see, the latter code choices is simpler and more compact. If code requires more lines and takes longer to write with return values, then what's even the point in using them?
question from:
https://stackoverflow.com/questions/65545879/what-is-the-point-in-returning-values 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…