• 0

[C++] int main(int argc, char* argv[])...


Question

Hey,

I've only done relatively simple console-based C++ programming and I've never used any parameters in the main() function. However, I see it quite frequently or every so often in sample or other people's code.

int main(int argc, char* argv[]) { ... }

What the hell is it for? :rolleyes: And why don't I see people actually using argc or the array argv[] in their program!

Thanks :yes: Hmm, there is probably no good reason I want to know this other than curiosity, heh... :rofl:

Link to comment
https://www.neowin.net/forum/topic/190198-c-int-mainint-argc-char-argv/
Share on other sites

11 answers to this question

Recommended Posts

  • 0

The argc and argv values are passed into the entry point when an application is executed by the runtime (mainCRTStartup.)

argc stands for Argument Count. This variable contains the number of arguments passed into the application.

argv stands for Argument Values. This is an array of strings which contains the values passed into the application. argv[0] is always the name of the application.

What they basically do is allow you to use the command line parameters passed to your application. Even if you declare them in main(), you are not forced to use them, however some compilers might give you a warning for "unused variable."

Hope that helps,

bwx

  • 0

Hey thanks for that answer man, got it. So in C++, you can declare it if you want, and you can use it if you want. I've done some basic Java, you don't seem to have the option there do you? If you leave it out the compiler seems to grumble... :(

  • 0

Dear fault,

you should declare argc and argv in any case.

As it's just clean coding. Java simply encourages clean coding.

Why you have not seen it is very likely because you have not looked very much at commandline tools.

imageing this pseudo applicaion:

$ switch -a fileA -b fileB

wich would simply copy fileA to fileB and fileB to fileA

now the code would look like the folloing ( PSEUDO CODE )

int
main (int argc, char * argv[])
{
  int i=0;
  char * a[20];
  char * b[20];
  if (argc < 5) // 1: switch, 2: -a, 3: fileA, 4: -b, 5: fileB
    return EXIT_FAILURE;
  for(i=1;i<argc;i++) // we can skip the first - switch is not importatnt to us.
  {
    if (argv[i][0] == '-' )
      switch (argv[i][1])
      {
         case 'a': a = argv[i+1];
         case 'b': b = argv[i+1];
      }
  }
}

I know there are lots of flaws in there. But I think your get the idea.

this would enable you to even run:

$ swicht -b fileB -a fileA

that's the use of argv,argc in real world up to my knowledge.

kindest regards,

Moritz "neofeed" Angermann

  • 0
you should declare argc and argv in any case. As it's just clean coding. Java simply encourages clean coding.

If you have need for command line parsing, by all means use them; however, it does use resources and if you have no intentions of using it... don't declare them...

  • 0

Cheers neofeed. I get where you're coming from. Didn't think of that...

Damn, you're a busy little dude. You should totally go into computer engineering then :D
Who me or neofeed? :huh:
If you have need for command line parsing, by all means use them; however, it does use resources and if you have no intentions of using it... don't declare them...
Good point, cheers for the advice.
  • 0
If you have need for command line parsing, by all means use them; however, it does use resources and if you have no intentions of using it... don't declare them...

yea right!, because they are in mem anyway, huh?

if you are such a resource nazi, you could do something like:

for(int i=0;i<argc;i++) free(argv[i]);
free(argc);
free(i);

at least now you don`t carry those `possible` arguments no longer in your holy resource reservoar.

kindest regards,

Moritz "neofeed" Angermann

  • 0
yea right!, because they are in mem anyway, huh?

if you are such a resource nazi, you could do something like:

for(int i=0;i<argc;i++) free(argv[i]);
free(argc);
free(i);

at least now you don`t carry those `possible` arguments no longer in your holy resource reservoar.

kindest regards,

Moritz "neofeed" Angermann

The point is that certain things do require minimal use of resources...

Second, a good rule of thumb to 'clean' programming is to use the least amount of resources as possible - declaring the command parsing variables does use resources, and it's a complete waste if you don't intend on using it...

Not to mention, it could add a fault or failure point within your code that isn't necessary...

True, it's not a major waste of resources, but it does make a difference, and adding something that isn't necessary or used is 'bad' programming

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • First time clicking on a Sayan Sen article after he started making clickbait, vague headlines recently. Didn't read, just came here to say the headline doesn't look like very cheap, vague clickbait this time. Are you okay?
    • Good review, and yeah the benchmark breakdown is pretty clear but also a little messy in a good way. It’s kinda interesting to see where the RX 9070 GRE slides in between the 7800 XT and the 9070 XT , especially when it comes to AI tasks and Blender style workloads. The side by side with Nvidia’s RTX 5070 and 4070 makes it feel obvious just how competitive the mid range GPU scene has gotten lately, and that’s great for creators and gamers too since you can pick based on your priorities rather than only chasing one single thing.
    • That's it. I finally uninstalled Firefox because they often keep pushing buggy updates, only to test them later and make users suffer. No longer is it my alternative browser to Edge. What a waste of energy. Firefox is bad for the environment, just like Chrome (wasting RAM/energy).
    • Microsoft Weekly: new Surface, Windows 11 26H2, and more by Taras Buria This week's news recap is here, with Microsoft announcing Windows 11 version 26H2, launching new Surface devices powered by Snapdragon X2 processors, GTA VI preorder date and cover art, fresh Windows 11 preview builds, a quirky phone-sized e-reader with a physical dial, and more. Quick links: Windows 10 and 11 Windows Insider Program Updates are available Reviews are in Gaming news Great deals to check Windows 11 and Windows 10 Here, we talk about everything happening around Microsoft's latest operating system in the Stable channel and preview builds: new features, removed features, controversies, bugs, interesting findings, and more. And, of course, you may find a word or two about older versions. Windows 11 version 26H2 is now official. Alongside Windows 11's new preview builds released this week, Microsoft confirmed version 26H2, which is coming later this year as an enablement package based on the same platform as versions 24H2 and 25H2. A newly published blog post details what IT admins should do to prepare for the upcoming launch. Next, we have new Windows 11 bugs. Users report that this month's security updates for Windows 11 cause all sorts of issues, including BitLocker bugs, OneDrive issues, black screens of death, and third-party integration in Office apps. Microsoft has not confirmed those yet, but it acknowledged other issues with its operating system. What Microsoft has confirmed is a bug where Recycle Bin delete prompts display internal file names instead of actual ones, and a year-old Windows JScript compatibility bug caused by security-focused engine changes. Moving to more positive news, Microsoft and Adobe are working on improving Windows performance in popular creative apps like Photoshop. Thanks to SPGO optimizations, users can expect up to 20% better performance. Finally, we have a few useful articles that can help you recover your PC or make it perform better. For one, we published a guide detailing what to do if your computer cannot boot after a clean Windows 11 install. There are two important steps you can try to get your system back to working in no time. Additionally, there is a more detailed guide on various CPU performance modes that could notably improve performance. Windows Insider Program Here is what Microsoft released for Windows Insiders this week: Builds Canary Channel Builds 28120.2315 and 29613.1000 These two builds include a new built-in audio driver, improvements to audio Settings, and more. Dev Channel Builds 26300.8697 and 26220.8690 Not much is available here. Some File Explorer improvements, Start menu enhancements, bug fixes, and more. However, build 26300.8697 is now officially marked as version 26H2. Updates are available This section covers software, firmware, and other notable updates (released and coming soon) delivering new features, security fixes, improvements, patches, and more from Microsoft and third parties. This week, Microsoft announced its newest Surface devices powered by Qualcomm's latest Snapdragon X2 processors. There is the 12th-gen Surface Pro and the 8th-gen Surface Laptop. Both devices feature little to no visual differences compared to their predecessors from 2024, and most changes hide inside, including a better processor, faster graphics, enhanced NPUs, and more. The Surface Laptop also received a new haptic trackpad. Mozilla is currently working on a major Firefox redesign, and earlier this week, it published a roadmap of upcoming features and highlights of the upcoming "Project Nova" rework. Files, one of the best file managers for Windows 10 and 11, has been updated in the Preview channel with a long-requested feature. Tree View is finally available in version 4.1.4, allowing you to quickly browse deeply nested folders without leaving the main view. In addition, the update improved the Windows Fonts folder, allowing you to preview each font without opening the default viewer. Rufus, another useful Windows 11 utility, also received a notable update. Version 4.15 arrived as beta with important fixes for silent Windows 11 installation. It also includes patches for ARM-based Windows PCs, OneDrive removal improvements, and more. Here are other updates and releases you may find interesting: Microsoft faces shareholder lawsuit over masking AI costs and slowing Azure growth Microsoft now allows you to tweak Visual Studio to new extremes Microsoft brings Planner Agent to all Microsoft 365 Copilot users Microsoft fixes one of Excel Copilot's most frustrating limitations Microsoft will finally let you sign in to Edge with a Google account Here are the latest drivers and firmware updates released this week: NVIDIA 610.62 with support for Empulse and various fixes. Reviews are in Here is the hardware and software we reviewed this week Earlier this week, we reviewed the DuRoBo Krono, a portable, phone-sized e-reader with some interesting physical controls. This device has an Apple Watch-like dial for page turning, frontlight adjustment, and more. Software is simple and no-nonsense, but it also lacks some useful features and customization. Overall, the device proved interesting, but not flawless. On the gaming side Learn about upcoming game releases, Xbox rumors, new hardware, software updates, freebies, deals, discounts, and more. Forza Horizon 6 received two big updates this week. Alongside the Series 2 content update, developers pushed plenty of bug fixes and balancing tweaks. However, they also had to acknowledge the Eliminator CR-farming exploit and shut down the online mode temporarily. Luckily, only a few days later, another fix arrived, which re-enabled Eliminator and patched the exploit. Microsoft announced new games for Game Pass subscribers. Those include EA Sports FC 26, Junkster, Call of Duty: Vanguard, Abyssus, RV There Yet?, and more. Some existing games are leaving the catalog, so be sure to check out the full list here. New games are also available for GeForce NOW subscribers, and they include Embers of the Uncrowned Demo, Aphelion, Megastore Simulator, OPERATOR, Citizen Sleeper, and more. Rockstart Games had plenty of GTA-related news this week. For one, the company gave GTA V players another free update. Those still playing the game on Xbox One and PlayStation 4 are no longer required to pay $40 to upgrade to the latest-gen version. More importantly, Rockstar Games revealed the GTA VI cover art and announced the preorder date. The Epic Games Store is giving away two games: Citizen Sleeper and Roboeat. These two titles are up for grabs until next Thursday, but if they are not up to your taste, you can always check out the latest Weekend PC Game Deal issue, which is usually full of discounts and specials that let you save a lot of money on new games. Great deals to check Every week, we cover many deals on different hardware and software. The following discounts are still available, so check them out. You might find something you want or need. GEEKOM X16 Pro at GEEKOM - $1,119.67 | 17% off Acer 4K Webcam for PC/Mac with All-Metal Unibody Sculpted - $59.99 | 14% off Samsung 990 PRO SSD 2TB - $369.99 | 42% off Nothing Ear Wireless Earbuds Bluetooth - $73.15 | 51% off PowerColor Reaper AMD Radeon RX 9070 16GB - $579.99 | 17% off This link will take you to other issues of the Microsoft Weekly series. You can also support Neowin by registering for a free member account or subscribing for extra member benefits, along with an ad-free tier option.
  • Recent Achievements

    • Week One Done
      Supreme Spray LV earned a badge
      Week One Done
    • One Month Later
      Genuinetonerink- Dubai earned a badge
      One Month Later
    • Week One Done
      Genuinetonerink- Dubai earned a badge
      Week One Done
    • One Year In
      hhgygy earned a badge
      One Year In
    • Week One Done
      AMV earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      506
    2. 2
      +Edouard
      163
    3. 3
      PsYcHoKiLLa
      84
    4. 4
      Steven P.
      74
    5. 5
      Michael Scrip
      71
  • Tell a friend

    Love Neowin? Tell a friend!