user1596683
user1596683

Reputation: 131

C++ odd thing with ampersand (&) in command argument

I just found out something rather strange here. It wasted me the better part of a day.

In MSVC, when an argument passed to the main program is abc&123, if one runs the program using the "Start Debugging" option, MSVC will pass the argument (one of argv[]) as "abc&123". But if one runs the program using "Start Without Debugging", MSVC will pass only "abc" and cut off whatever after the "&". What is the reason behind this?

Upvotes: 0

Views: 827

Answers (1)

Arashium
Arashium

Reputation: 325

& is interpreted as a new command in your command line. nothing wrong with your code. OS interpret!

Create following code and test!

#include <iostream>

using namespace std;

int main(int argc,char *argv[])
{
    for(int i=0;i<argc;i++)
        cout<<"arg "<<i<<": "<<argv[i]<<endl;
    return 0;
}

test followings in command line:

appname aaa& bbb

appname "aaa& bbb"

The first line is interpreted as two separate commands:

appname aaa
bbb

while the second one is only one command:

appname "aaa& bbb"

This is the mechanism defined in shell and OS from back to MS-DOS. Quotations change the order of tokens similar to parenthesis in mathematics.

Update:

The debugger does pass the variable from different process. It knows that & is not referring to a new command. Start without debugging is more accurate. You may call it bug in the debugger.

Upvotes: 2

Related Questions