My friend wrote a program to write a sentence backwards when the user gives input. Neither one of us can figure out why this is working, but it works every time...
while (str[length-i] > str[i])
We both agree that both of these values are characters and comparing them will access their ASCII values. I can see how coincidence can sometimes make the two characters we want compared to fit the condition, but not every time. I made sure to type in sentences that would make the two characters in a certain alphabetical relationship.
I hope that someone can help us understand this.
We wasn't really looking for a code,we were just amaized that that one works.But friend explaind me now why is it that way,but tnx anyway for posting :)
There's a lot of useless code in there. This is the only code that makes sense:
Tresky wrote:
1 2
for (int s = length; s >= 0; s--)
cout << str[s];
(sic)
This's what's doing the actual backward printing; the rest is excess baggage. All of this is useless:
Tresky wrote:
1 2 3 4 5 6 7 8 9 10 11 12
int length = str.length();
int c;
for (int i = 0; i < length; i++) {
while (str[length-i] > str[i]) {
c = str[i];
str[i] = str[length-i];
str[length-i] = c;
}
if ( str[i] >= str[length-i])
break;
}
(sic)
Yes, I know that length is used but, std::string::length( ) performs the eact same thing. length is effectively redundant and a waste of 4 bytes.
@Framework: a variable for length isn't redundant, it's a time space trade off. You are using more memory, but in return, you don't need to waste time calling a function to calculate length. Even if it keeps the value and doesn't compute it every time, it is still more time to enter the function then leave. While something this minute doesn't make a difference, in larger calculations it adds up.
Intrexa, If they cut out that ineffective for loop construct, std::string::length( ) would only need to be called once. In addition, they would save 8 bytes of stack space, resulting in low memory usage (hardly noticeable, but it's a performance increase). Not only that, they would also save those precious clock-cycles.
Compilers are smarter than we give them credit for. I'm sure they'd take one look at this simple exercise and spit out nearly the same assembly for either situation.
Clarity > [edit]Attempted[/edit] Optimization in my book. Amen.