开发者

What happens when you don't follow the practice of argv and argc [duplicate]

开发者 https://www.devze.com 2023-03-16 05:29 出处:网络
This question already has answers here: 开发者_开发知识库 Closed 11 years ago. Possible Duplicates:
This question already has answers here: 开发者_开发知识库 Closed 11 years ago.

Possible Duplicates:

main(int argc, char *argv[])

Main's Signature in C++

If i write:

int main(int argc, char** argv)

i get proper commandline input. What would happen if i wrote say,

int main(int foo, double fooDouble, fooType FooVar)

Is this OS-dependent or does it depend on the compiler?


Given that it does compile, it will still only be called with the argc and argv arguments.

So your fooDouble will get the pointer value of argv, and FooVar will get whatever value is in that register/stack space used for that argument position (which may not have been initialized by the callee, so it may hold any undefined value).


This code doesn't even have to compile. If it does, undefined behaviour may occur.


The effect of adding a third (or fourth, or fifth...) argument to main indeed depends on the operating system. For instance, on Windows (and I believe on Unix as well) you can have a third argument which grants access to the environment variables:

int main( int argc, char **argv, char **env )


The C standard (BS ISO/IEC 9899:1999) gives two alternatives for main:

int main(void) { /* ... */ }

and

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

It also allows equivalents, so an argv of char ** argv for example. Additional arguments are "neither blessed nor forbidden by the Standard". Such addtions will be compiler and runtime (not operating system) specific.

The arguments are passed by the C runtime, which calls main(). Passing any other type would be problematic on general environments like Windows and UNIX, so quite how you would expect to pass a double or fooType is beyond me.

Invoking a program from either a command-line or using interfaces like execve (UNIX) or CreateProcess (Win32) involves passing zero delimited strings. In theory you could hack it to pass a binary value and then cast it in main, provided it does not contain a '\0' anywhere except at the end, which would be challenging.

EDIT: it occurs to me that you can call main() from within your program - the well known obvuscated C code "The twelve days of Christmas" does this. In this case there is no reason why you can pass anything the prototype allows.

0

精彩评论

暂无评论...
验证码 换一张
取 消