0

Im not sure about how it works but is it possible to pass parameters to a main() function like any other function in C? If so, please explain how it works?

  • 2
    Does this answer your question? [Pass arguments into C program from command line](https://stackoverflow.com/questions/498320/pass-arguments-into-c-program-from-command-line) – Kfir Ventura Apr 21 '21 at 06:56
  • Notably, the application programmer does not get to decide the format of main. Only the compiler can do that. It is required to support `int main(int argc, char* argv[])` if the compiler is a "conforming hosted implementation" (meaning C compliant compiler for programs running on an OS). It may additionally support compiler-specific forms, in which case you have to read the compiler documentation to find out which ones. – Lundin Apr 21 '21 at 09:45

1 Answers1

0

You can't "pass parameters" to it because you can't call it per-se. It's the entry point of your application. It gets parameters from the parent process via the operating system.

int main(int argc, char** argv) is how you receive the arguments. How you "send" them is done by an exec call of some variety, like execv().

This is how your shell sends in arguments, so if you run:

./myprogram arg1 arg2

Then you have those arguments available. Note that argv[0] is the name of the program or the "zeroth" argument, which in this example is the "./myprogram" part.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • What exactly makes it so that you can't call it? Insofar I know, you can also call it like any other function. – Emanuel P Apr 21 '21 at 11:06
  • @EmanuelP If you call `main()` from a function called from `main()` you're asking for runaway recursion. If you make it so it can be called recursively I have no idea why you'd go through that trouble, it just doesn't make any sense. There's a lot of things you can *technically* do in C, but which are so outside the realm of convention for all purposes they should not be done. That's why I say "per-se". – tadman Apr 21 '21 at 23:52