Jump to content

  • Log In with Google      Sign In   
  • Create Account


#ActualChad Smith

Posted 29 April 2013 - 01:06 AM

Some practical everyday uses:

 

// I want to trigger something every 7 executions:

static int count = 0;

count = ++count % 7;

if( count ) {do something}

 

// I want to cycle 0-6 repeatedly.

static int count = 0;

count = ++count % 7;

 

In the first case the 'if' relies on the fact that the only "true" condition is when something is zero.  In the second case a value modded by any higher value results in the same value, it goes to zero when modded with itself.  Basically a variable in both cases is going to step from 0 to mod value minus one, or 0-6 in this case and keep repeating.

 

I think I use the first case with the 'if' statement more often but I know I use the second case on occasion also.

EDIT: Nvm, no reason for this post I guess.  lol.  Typo.  :)

 

Like Khatharr said, in C/C++ it would actually execute every time except when count is 0.

 

As a quick test:

 

for(index = 0; index < 10; ++index)
{
     count = ++count % 7;
     if(count)
     {
          std::cout << count << " ";
     }

}

produced output:

1 2 3 4 5 6 1 2 3

#1Chad Smith

Posted 29 April 2013 - 01:05 AM

Some practical everyday uses:

 

// I want to trigger something every 7 executions:

static int count = 0;

count = ++count % 7;

if( count ) {do something}

 

// I want to cycle 0-6 repeatedly.

static int count = 0;

count = ++count % 7;

 

In the first case the 'if' relies on the fact that the only "true" condition is when something is zero.  In the second case a value modded by any higher value results in the same value, it goes to zero when modded with itself.  Basically a variable in both cases is going to step from 0 to mod value minus one, or 0-6 in this case and keep repeating.

 

I think I use the first case with the 'if' statement more often but I know I use the second case on occasion also.

 

Like Khatharr said, in C/C++ it would actually execute every time except when count is 0.

 

As a quick test:

 

for(index = 0; index < 10; ++index)
{
     count = ++count % 7;
     if(count)
     {
          std::cout << count << " ";
     }

}

produced output:

1 2 3 4 5 6 1 2 3

PARTNERS