Solving Problem 1 Using Windows Batch files

As crazy a it sounds, it turns out it is possible to solve Project Euler problem 1 using Windows Batch files! It is possible because modern versions for cmd support delayed expansion of variables, and arithmetic expressions using “SET /A”.

Delayed expansion means that variables are expanded at runtime, rather than parse time. Normally %VARIABLE% will be expanded once with whatever value it contains before the script is run, however with delayed expansion we can use !VARIABLE!. This variable is expanded whenever that line is executed, which with a for loop could be multiple times.

@echo off
setlocal enabledelayedexpansion

set /a sum = 0
FOR /L %%L IN (1, 1, 999) DO (
    set /a mod = %%L %% 3
    IF NOT !mod! EQU 0 set /a mod = %%L %% 5
    IF !mod! EQU 0 set /a sum = sum + %%L

echo %sum%

Managing Multiple Versions of Visual Studio

In my previous post, I described how to build an old version of GNU Make for Windows. While working on that I wanted to be able to test out different versions of Visual Studio to see if it builds successfully. Quickly switching between versions of Visual Studio was difficult so I created a batch file to help make it a lot easier.

This script takes a single argument that specifies which version of visual studio you want to set up and it then calls the appropriate vsvars32.bat file for that version of Visual Studio.

@echo off

if "%1" == "vs4" goto vs4
if "%1" == "vs6" goto vs6
if "%1" == "vs2003" goto vs2003

goto argerror

pushd C:\msdev\bin
call vcvars32 x86
goto done

pushd C:\Program Files\Microsoft Visual Studio\VC98\Bin
call vcvars32
goto done

pushd "C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Tools\"
call vsvars32.bat
goto done

echo no Visual Studio version specified!
echo usage: setupenv [version]
echo    where version is one of the following: vs4, vs6, vs2003