View Single Post
Old 10-11-2004, 02:28 PM   #2 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
A lot .
But first thing first. Try to use the CODE tags. Insert your code between [ code ] and [ /code ].
Here, compare these:
Code:
 #include <iostream>
#include <cstdlib>

using namespace std;

void odd();
void odd(int x);

int main()
{
   odd();
   cout<<endl;
   
   odd(4);
   cout<<endl;
   
   system("PAUSE");
   return 0;
}

void odd()
{
   int x(0);
   while (x<=10)
   {
      if (x % 2 == 0)
         cout << x << " is even";
      else
         cout << x << " is odd";
      { ++x; cout<<endl; }
   } 
}

void odd(int x)
{
   if (x % 2 == 0)
      cout << x << " is even";
   else
      cout << x << " is odd";
}
The usage of these two functions are different, although they are fundamentally the same functions. If I could remove the double code, it will show. The core of the application is if (x % 2 == 0). So if could extract this test from both the functions, I could make things a little less memory consuming without critical speed (if any speed is lost to start with). And besides, we'd like to seperate messages from the critical functions. So I'll do that too. Later, when you build controllers and engines and alike (these do the "clever" part of a program), you'd like to seperate the views from everything else.
Code:
 #include <iostream>
#include <cstdlib>

using namespace std;

bool odd(int x);
void odd_even_msg(bool m);
void range_test_odd();

int main()
{
   range_test_odd();
   system("PAUSE");
   return 0;
}

////////////////////////////////////// bool odd(int x)
{
   if (x % 2 == 0)
      return false;
   else return true;
}

////////////////////////////////////// void odd_even_msg(bool m)
{
   if(m)
      cout<<"is even"<<endl;
   else
      cout<<"is odd"<<endl;
}

///////////////////////////////////////// void range_test_odd()
{
   for(int i = 0; i<11; ++i)
   {
      cout<<i<<' ';
      odd_even_msg( odd(i) );
   }
}
__________________

Last edited by Valmont; 10-11-2004 at 03:14 PM.
Valmont is offline   Reply With Quote