++Variable vs Variable++ and it's purpose

I have been writing code professionally for about 5 years now and through the entirety of that time I have never needed to use ++variable_name. I just always simply used variable_name++ and that was that. Moreover, I never really even understood what the first way of incrementing did, to me it was all the same and was just a personal preference on how a developer wanted to write their code.

However, today, I have finally discovered the reason for using ++variable_name instead of variable_name++!

I discovered the difference when I was writing code to create a dual-zero padded numerical count (i.e. 001, 002, etc). So I wrote my code the way that I thought and it wasn't working and it took me a minute to figure out. In the end, it was due to me using variable_name++ in a function call. Well, since variable_name++ doesn't actually increment the number until last, it was passing the same number into the function call over and over again and therefore returning the same value over and over again. See my original code snip below:

#!/usr/bin/perl
use strict;
use warnings;

my $count = getCount();
print "Count: ${count}\n";

for(my $x = 0; $x < 10; $x++){
  #> notice the variable_name++ in the fuction call!
  $count = getCount($count++); 
  print "Count: ${count}\n";
}


#> custom routine to increment count
sub getCount
{
  my $rv;
  if(defined($_[0])){
    $rv = 0+$_[0];
  }
  else{
    $rv = 1;
  }
  return(sprintf("%03d", $rv));
}

1;

This would then produce the following output:

> perl test_counter.pl
Count: 001
Count: 001
Count: 001
Count: 001
Count: 001
Count: 001
Count: 001
Count: 001
Count: 001
Count: 001
Count: 001

As you can see all the values are the same. This is due to the $count++ not actually updating the value before it is passed to the function call and therefore it is always the same value.

Now if you consider this code:

#!/usr/bin/perl
use strict;
use warnings;

my $count = getCount();
print "Count: ${count}\n";

for(my $x = 0; $x < 10; $x++){
  #> notice the ++variable_name in the fuction call!
  $count = getCount(++$count); 
  print "Count: ${count}\n";
}


#> custom routine to increment count
sub getCount
{
  my $rv;
  if(defined($_[0])){
    $rv = 0+$_[0];
  }
  else{
    $rv = 1;
  }
  return(sprintf("%03d", $rv));
}

1;

we changed it so that it now is ++$count which is actually incrementing the variable prior to sending it to the function thus resulting in the following output:

> perl test_counter.pl
Count: 001
Count: 002
Count: 003
Count: 004
Count: 005
Count: 006
Count: 007
Count: 008
Count: 009
Count: 010
Count: 011

Thanks for reading!

Don Oerkfitz

Read more posts by this author.