Which of the two programs is better and why? [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Code 1
int A, B, MAX;
cout << "Give two numbers:" << endl;
cin >> A >> B;
if (A > B)
{
MAX = A;
}
else
{
MAX = B;
}
cout << "Largest amongst given numbers is: ";
cout << MAX << endl;
return 0;
Code 2
int A, B, MAX;
cout << "Give two numbers:" << endl;
cin >> A >> B;
MAX = A;
if (B > MAX)
{
MAX = B;
}
cout << "Largest amongst given numbers is: ";
cout << MAX << endl;
return 0;
In above program logic, which one is best and why? is there any difference between them.? it is my exam question i would like to ask stack overflow to know best opinion.

MAX = std::max(A, B);
Is better than both in terms of clarity.
In terms of speed, the compiler should be able to optimise any of these methods to be equivalent; but again I'd favour std::max because I'd sooner trust the compiler to optimise a standard function than some arbitrary made up code to perform the same task.

They are the same so I would prefer code 1 because it's more readable. In both cases you have to bring both A and B into a register (regardless) and then do a single comparison (regardless). And it won't write out to the variable MAX until after this segment is done (because it won't need to kick anything out of a register).
This isn't something that is going to cause any kind of performance gain. In fact, it's possible (although I doubt it) that the compiler would compile them the same (the compiler does all kinds of code modification to create an optimal set of instructions).
As suggested the only thing that likely would give a performance gain is using the library function std::max. This is because the compiler will basically perform the comparison in the most efficient way (likely without even calling a conditional jump). If your two values are integers, then you can see here that it's possible to find the max with five integer operations (all of which, except the multiplication can generally be done in a single cycle). You generally want to avoid conditional jumps as much as possible and this algorithm does that. Most likely the max function does something like this or similar (but it would have to be different for floating point values).

After MAX = std::max(A,B), the next best code is:
MAX = A > B ? A : B;
If you don't want to use that, then I prefer your "code 1" because:
code 2 always sets MAX = A, which is momentarily misleading and only becomes clear as the later code is studied; while this issue is common in C++ and many other languages, there's no particular reason to embrace that complication when it's easily avoided
for some types (the question didn't originally specify int), an assignment may be an expensive operation (e.g. copying a lot of data), so always assigning once is better than potentially assigning twice
For both those reasons, it also desirable to declare and define MAX in one step. It may not be practical if say it's a non-const reference accepted as a function argument, but when it is possible it's another good reason to prefer std::max or the ternary ? approach: you won't need a misleading and potentially inefficient or unavailable default construction. (Now you've changed the question to be int specific, the expense of copying and construction is known and trivial, and the optimiser can be counted on to remove them in most cases).

I would say use code 2. It is better because you explicitly say that if MAX B is greater than MAX A, then change MAX to B. In the other one, you don't have any defining factors about why MAX A is greater than MAX B. From what I see, you will probably have a harder time using code 1 than code 2.

Related

Why is this variable returning 32766?

I wrote a very basic evolution algorithm. The way it's supposed to work is that the user types in the desired value, and the amount of generations to try to reach it. Then, the program will run through, taking the nearest value in an array to the goal and mutating it four times (while also leaving the original, in case it's right) to try and get closer to the goal. In theory, it should take roughly |n|/2 generations to reach the value, as mutations happen in either one or two points.
Here's the code to demonstrate what I mean:
#include <iostream>
using namespace std;
int gen [5] = {0, 0, 0, 0, 0}; int goal; int gens; int best; int i = 0; int fit;
int dif(int in) {
return abs(gen[in] - goal);
}
void nextgen() {
int fit [5] = {dif(1), dif(2), dif(3), dif(4), dif(5)};
best = *max_element(fit, fit + 6);
int gen [5] = {best - 2, best - 1, best, best + 1, best + 2};
}
int main() {
cout << "Goal: "; cin >> goal; cout << "Gens: "; cin >> gens;
while(i < gens) {
nextgen(); cout << "Generation " << i + 1 << ": " << best << "\n";
i = i + 1;
}
}
It's pretty simple code. However, it seems that the int best bit of the output is returning 32766 every time, no matter what I do. Do you know what I've done wrong?
I've tried outputting the entire generation (which is even worse––a jumbled mess of non user friendly data that appears meaningless), I've reworked the code, I've added varibles and functions to try and pin down exactly where the error is, and I watched the entire code aesthetic youtube channel to make sure this looked good for you guys.
Looks like you're driving C++ without a license or safety belt. Joke aside, please keep trying and learning. But with C/C++ you should always enable compiler warnings. The godbolt link in the comment from #user4581301 is really good, the compiler flags -Wall -Wextra -pedantic -O2 -fsanitize=address,undefined are all best practice. (I would add -Werror.)
Why you got 32766 is possible to analyze with a debugger, but it's not meaningful. A number close to 32768 (=2^15) should trigger all the warning bells (could be an integer overflow). Your code is accessing uninitialized memory (among other issues), leading to what is called undefined behaviour. This means it may produce different output depending on your machine, compiler, optimization flags, OS, standard libraries, etc. - even adding a debug-print could change what it does.
For optimization algorithms (like GAs) it's also super easy to fool yourself into thinking that your implementation is correct, because the optimization will find a way to avoid (or exploit) any bugs. I've had one in my NN implementation that was accessing some data from the previous example by accident, and it took several days until I even noticed there was a problem.
If you want to focus on the algorithms, I suggest to start with a different language (anything except C/C++/Assembly). My advice would be either Python (though it can be 50x slower, it's much easier to learn and write) or Rust (just as fast as C++ and just as complicated, but no undefined behaviour). With Rust, every mistake in your code above would have given you either a warning by default, a compiler error, or a runtime error instead of wrong output. Though C++ with the flags mentioned above does the same for your specific code.

Iterative or Recursive Factorial [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've implemented factorial recursively this way:
int factorial(int x){
if (x <= 0)
return 1;
else
return (x*factorial(x - 1));
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Please enter your number :::";
int x;
std::cin >> x;
std::cout<<"factorial(" << x << ") = "<< factorial(x);
getchar(); getchar();
}
which way of implementing such code is more useful writing it using iteration and loops or writing it recursively such as above?
It depends on the number itself.
For normal-range numbers, recursive solution could be used. Since it makes use of previous values to calculate future values, it can provide the value of 'factorial(n-1)' on the fly.
factorial(n) = factorial(n-1) * n
However, since recursion makes use of stacks, it would eventually overflow if your calculation goes deeper than the stack-size. Moreover, recursive solution would give poor performance because of heavy push-pop of the registers in the ill level of each recursive call.
In such cases, iterative approach would be safe.
Have a look at this comparison.
Hope it helps!
In C++ a recursive implementation is usually more expensive than an iterative one.
The reason is that each call causes a creation of a new stack frame which holds data such as return address, local variables and registers that are needed to be saved. Therefore a recursive implementations requires amount of memory which is linear with the depth of your nested calls while iterative implementations use a constant amount of memory.
In your specific case, which is tail recursion, a compiler optimization may switch the function call with a direct jump preventing the unnecessary usage of memory on the call-stack.
For more detailed explanation you might want to read:
Is recursion ever faster than looping?

Defining variables vs calculating on the fly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In terms of readability and memory usage/ processing speed is it better to define a variable, modify it and output the variable or to just output a result? eg:
int a = 1, b = 2, c;
c = a+b;
std::cout << c << std::endl;
vs
int a = 1, b = 2;
std::cout << a+b << std::endl;
Thanks
Well with this example processing speed and space is negligible. So small and so few instructions.
But in the grand scheme of things the answer is -- well it depends.
The term "better" is in the eye of the beholder. What is better for one program might not be better for another (this includes readability). What may work in one instance may not work in another. Or in the end it could be negligible (arithmetic instructions are pretty fast depending on the scope of what you need and int, double, char, float data types are relatively small and well defined so you know how much memory you are taking up).
Here you do not define if these variables were declared on the stack or the heap. If on the stack then it doesn't matter if you declared it because after the function that these variables live in ends, the memory gets released. If on the heap you may not want to declare millions of variables just to sit there. But then again you may need them there.
So its based almost entirely on a case by case bases when dealing with bigger projects.
And you tell me what is better here?
int result = (3434*234+3423-4/3*23< 233+5435*234+342)? (int)(234+234+234234/34):(int)(2+3*234);
std::cout << result << std::endl;
OR
double x = 3434*234+3423-4/3*23;
double y = 233+5435*234+342;
double a = 234+234+234234/34;
double b = 2+3*234;
int result = 0;
if( x>y) result = a;
else result = b;
std::cout << result << std::endl;
in the end it these do the same things are the same with negligble difference but which one is easier to read?
Your question on memory is easy to answer, variables are stored identifiers so each take a couple bytes (bytes store 8 bits or binary digits) to store. That being said, a byte is almost no memory, meaning that ultimately it has no net effect. In terms of RAM (or Random Access Memory) a byte is again, almost negligible meaning that defining a, b, and c is barely slower than just calculating a + b. Makes sense?

Shift operator fast or not fast? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the faster between the two following code? why?
In which case one can be preferred to the other?
double x = (a + b) >> 1
double x = (a + b) / 2.0
These do different things so pick the one with the functionality you like: Truncating the result down or returning the 0.5 fraction.
"Premature optimization is root of all evil". Use what is more readable, when you have perfomance issue first look for algorithms and data structures, where you can get most perfomance gain, then run profiler and optimize where is necessary.
As others have said, the two statements produce different results, especially if (a + b) is an odd value.
Also, according to the language, a and b must be integral values in order to satisfy the shifting operation.
If a and b differ in type between the two statements, you are comparing apples to elephants.
Given this demo program:
#include <iostream>
#include <cstdlib>
#include <cmath>
using std::cout;
using std::endl;
int main(void)
{
const unsigned int a = 5;
const unsigned int b = 8;
double x = (a + b) >> 1;
cout << x << endl;
double y = (a + b) / 2.0;
cout << y << endl;
return EXIT_SUCCESS;
}
The output:
6
6.5
Based on this experiment, the comparison is apples to oranges. The statement involving shifting is a different operation that dividing by a floating point number.
As far as speed goes, the second statement is slower because the expression (a + b) must be converted to double before applying the division. The division is floating point, which may be slow on platforms without hardware floating point support.
You should not concern yourself on the execution speed of either statement. Of more importance is the correctness and robustness of the program. For example, the two statements above provide different results, which is a very important concern for correctness.
Most Users would wait for a program to produce correct results than have a quick program producing incorrect results or behavior (nobody is in a hurry for a program to crash).
Management would rather you spend time completing the program than wasting time optimizing portions of the program that are executed infrequently.
If a or b is a double or float, shifting will produce incorrect results.

Translating data from one type to another in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I wanted to understand how type conversion happens in a professional grade software?
Consider the following conversions:
int to double
double to int
string to double
double to string
Currently I am using Qt for my project, which has API for doing these tasks.
So I just wanted to know how people perform these conversions with standard C++ only.
Accuracy, speed & memory are the priorities in their respective order.
For int to double you can simply do static_cast<double>(int_value);
from double to int it depends on the case , most of the time static_cast would do , however, sometimes you need to have specific control over the value being rounded to int. For this you can use functions like floor, round , or ceil.
For string to anything and anything to string there are a couple of options:
snprintf() - not recommended unless you know what you are doing. accuracy is hard to control
stringstream / istringstream - this has good accuracy and easy to controll
boost::format - personal favorite, check doc: http://www.boost.org/doc/libs/1_53_0/libs/format/doc/format.html
In terms of performance it depends i would pick snprintf to be the fastest in certain cases since it does not require allocations.
The first one is often implicit (since it's a promotion). The first and the second one can be accomplished with a simple static_cast:
double x = 0.123;
int y = 123;
std::cout << static_cast<int>(x) << '\n';
std::cout << static_cast<double>(y) << '\n';
The third one would require a std::istringstream:
std::string x = "123.456";
double y;
std::istringstream ss(x);
ss >> y;
The fourth would require a std::stringstream:
double x = 123.456;
std::stringstream ss;
ss << x;
ss.str(); // your string
int to double is a promotion in C++, which can be done implicitly.
double to int can also be done implicitly but it should be use with caution since many doubles either don't represent round integral values or are too big to be converted. Most compilers warn about that loss of precision, so the cast should be made explicit to get rid of the warning - if you are sure you are doing the right thing.
string to double, double to string: These are normally used only for input/output (GUI, console, textfiles, ...). Numerical values should be handled inside the program as such and not as strings. You should prevent double->string->double conversion chains inside your program when possible, since both conversions are not accurate and prone to rounding and other errors.