patterncppMinor
Is the Number Less than
Viewed 0 times
numberthantheless
Problem
Can my code be reviewed by common C++ formatting standards, and can it be optimized? My code determines if the number (x) you input is greater then the other number (y) you input, the code then prints out the results.
#include
#include
using namespace std;
int oper();
int main() {
oper(); //function for the operation.
}
int oper() {
int x = 0;
int y = 0;
int c;
std::cin >> x;
std::cin >> y;
if (x > y)
cout << "\nx = " << x <<
", y must be < " << x << "\n";
}Solution
using namespace std;You import
using namespace std;, but you actually only use it in your call to cout. As a general rule, you don't want to import this in its entirety, but to call the components directly, like in your calls to std::cin. See Why is using namespace std considered bad practice for more information.Function Declaration
As a general rule, you order C++ functions from last used to first, unlike in Java. That means your
oper() method would typically be written above your main() method. Typically, you only explicitly declare functions in header (.h) files, and when two functions call each other and you do not have a .h file to go with your .cpp file.Comments
Please do not use comments when it is obvious what is happening. Your only comment here does not help understand either the how or why of the program.
Style
Please use braces around your
if statements. At first, I thought you had a bug here because of the two lines, but then I realized it was just a line break in a single statement. Braces would help clear this up, as would writing the statement either on one line, or with better indentation as:cout << "\nx = " << x
<< ", y must be < " << x << "\n";Error Handling
Your program has absolutely no error handling, and that is perfectly understandable at this point. Eventually, however, you will need to use a
try block to ensure your program will not crash if the user enters invalid input and a loop to ensure a valid value is eventually entered. Bjarne Stroustrup's "Programming: Principles and Practice Using C++" dedicates the majority of several chapters to proper error handling, and I strongly recommend you read this book; it will help you with your Java programming as well as your C++ programming.Improvements
You only output the result if the
x value entered is greater than the y value entered. Your program should output the result when y is greater than x, and when x is the same value as y as well.Code Snippets
cout << "\nx = " << x
<< ", y must be < " << x << "\n";Context
StackExchange Code Review Q#149459, answer score: 4
Revisions (0)
No revisions yet.