Reputation: 12797
Why this code prints 1 instead of 5
Code:
main(int x=5) //this defn. is written intentionally to chec weather main accepts
expression or not.
{
printf("%d",x);
}
Compiler used:minGW 3.2
EDIT
My point is weather x=5
executes or not. if not then why i don't get any error or warning.
Upvotes: 0
Views: 147
Reputation: 158469
Update
Your main
declaration is not valid, if we look at the C++ draft standard section 3.6.1
Main function paragraph 2 says(emphasis mine):
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both
— a function of () returning int and
— a function of (int, pointer to pointer to char) returning int
So main
should adhere to one of these standard forms or implementation defined forms defined by compiler documentation.
gcc
gives me a warning for this regardless of warning levels and in clang
this is an error, so I am not sure why you do not see an error.
Orignal Answer
The first argument to main is the argument count usually denoted as argc for example:
int main(int argc, char *argv[])
{
}
and argv is an array of string which represents the arguments to your program, the first one being the command line.
Upvotes: 1
Reputation: 68140
Because the operating system expects this signature of main
:
int main(int argc, char** argv);
argc
is the amount of parameters. When it calls your main
, it passes the amount of arguments (argc
) as the first parameter, which is 1 (if you call your binary without arguments, you still get one argument: the binary filename, $0
in bash).
Note that this depends also on the C ABI. By the C/C++ standard, multiple signatures of main
are allowed. So, depending on the compiler and the OS, there could be a different handling for main
. What you are doing is not really defined behavior.
You should declare main
like the expected - because that is what your OS expects and uses. Make another function for whatever you want to program.
Upvotes: -1
Reputation: 76275
In void f(int x = 5)
, the = 5
part is a default argument. You can call the function in two different ways:
f(); // uses default argument, as if f(5)
f(3); // explicit argument
Note that the decision to use the default argument is made at the point of the call, not at the point of the declaration. Regardless of whether int main(int x = 5, char *argv[])
is valid, the application's startup code (part of the compiler's library) won't know about the attempted default argument, so won't do anything with it. And don't try and get tricky by calling main
from inside your program: that's not allowed.
Upvotes: 1
Reputation: 14376
because x is really argc (and your count of arguments is 1)
The signature for main is:
int main (int argc, char **argv)
with argc being a count of arguments
and argv being an array of those arguments
Upvotes: 10