Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Main with single argument

Tags:

c

c89

I've recently come across a C program in which the main function only took a single argument. Is this legal in C89? gcc didn't seem to have any problems with it.

What I think happens is that the signature is ignored and main is called as main(int,char**) anyways, but I'm not sure.

It looks like this in the program: main(argc) { ... }

like image 205
Cubic Avatar asked Nov 07 '25 03:11

Cubic


2 Answers

According to the C89 standard, it is not legal. From section 2.1.2.2 Hosted environment:

The function called at program startup is named `main`. The implementation
declares no prototype for this function. It can be defined with no parameters:

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

or with two parameters (referred to here as argc and argv , though any names
may be used, as they are local to the function in which they are declared):

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

The C99 standard states the same in section 5.1.2.2.1 Program startup.

like image 82
hmjd Avatar answered Nov 09 '25 10:11

hmjd


Yes, it works, but it is useless.

Remember that in C, any variable that doesn't have a type specified defaults to int, so that means that the function expands to this:

int main(int argc) {
    ...
}

Which is legal in C89. Most of the time, however, if you want to know the number of arguments sent to a program, you probably want the contents of those arguments, so this is mostly useless.

However, GCC (when compiled with -Wall) gives me a warning:

Only one parameter on 'main' declaration.

It's just saying that this code is pretty much useless.

However, technically, as @hmjd noted, this is illegal, in that it is undefined behavior. However, in most implementations of C that I have came across, when you pass extra parameters to a function, they are just ignored for the most part. So, unless you are on a system where it matters if you overflow the amount of variables sent to a function, you should be fine.

like image 42
Richard J. Ross III Avatar answered Nov 09 '25 08:11

Richard J. Ross III



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!