Variables declared in a Loop

Ran into a very subtle issue today with variables declared in a loop. For pcreminder.com, I have an outer loop that gets all the reminders that need to be sent for all users. Within that loop, there is a second loop that loops through all the receipts for the reminder and sends the actual reminder. I have a reminder counter that keeps track of the number of reminders sent so that I can update the users count for the month. Let’s look at a very simplified version of this code:

2014-12-31_0907

So as you see in the above example, I have 20 reminders to send. Each reminder has 10 recipients.

Now for a Pop Quiz: Assuming that each reminder is for a separate user, how many reminders will each user be charged for?

If you answered 10, you were wrong!

The first user will be charge with 10, the second with 20, the third with 30, etc. Let’s take a look at the trace window to confirm this:

2014-12-31_0911

Apparently WX doesn’t redeclare the variable with each loop, which makes sense as that could lead to a memory leak, however I was expecting it to be reinitialized. It is a simple fix all we need to do is change the declaration to also clear the variable, like this:

ReminderCount is int = 0

And now if you run the code the trace window looks like this:

2014-12-31_0914

So as you see, not a hard issue to fix, but if you are not careful with your coding, you can definitely get an unexpected result, like say a bunch of users complaining because they are getting “Over Your Limit” email messages!

Now, back to your regular schedule program….

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s