The %~dp0 Variable

Reblogged from

The %~dp0 (that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.

The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.

If you follow the percent character (%) with a tilde character (~), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. The d modifier expands to the drive letter and the p modifier expands to the path of the parameter.

Example:  Let’s say you have a directory on C: called bat_files, and in that directory is a file called example.bat. In this case, %~dp0 (combining the d and p modifiers) will expand to C:\bat_files\.

Check out this Microsoft article for a full explanation.

See also this thread on stackoverflow.

This differs from the %cd% variable which is the current directory.

You can easily see the difference by creating the following batch file called, say, test.bat
@echo off
echo The current directory is %cd%
echo The batch file is in %~dp0

If you were to run this from d:\temp by calling c:\bin\test.bat then the output would be
The current directory is D:\temp
The batch file is in c:\bin\


For my current contract I finally have access to a C++11 compiler, and am starting to use C++11 in a production environment. Yes, I’m late to the party but that’s what happens when you have a succession of clients using older compilers.

I’m only scratching the surface so far, but things I am really liking so far are the auto keyword, initialiser lists, and the extensions to the for command to make iteration more compact.

Consider the following traditional C++ code for initialising a vector and then iterating over it:

std::vector<int> myVector;

for (std::vector<int>::const_iterator it = myVector.begin(); it != myVector.end(); ++it)
    std::cout << *it << std::endl;

Now consider the same code written in C++11

std::vector<int> myVector = { 1, 2, 3, 4, 5 };

for (auto elem : myVector)
    std::cout << elem << std::endl;

Life just got a whole lot more convenient.


Note that for more complex types where there is a significant cost to copy, you would probably want to use the following instead:

for (const auto& elem : myVector)