C: Can there be two main() functions in a program? - c

I saw other questions about having two main()'s in C program:
I'm using CodeBlocks
But please consider this program:
void main()
{
void main()
{
printf("hello!");
}
printf("World!");
}
prints only "World!".
I'm actually writing these kind of code pieces to check what's happening under the hood.
I somehow get the doubts( as i get errors and unexpected behaviours in my programs ) by writing weird codes but I'm unable to know why they happened
Is there any reference to C language that i can refer to?
Thanks in Advance.

C: Can there be two main() functions in a program?
No.
And the code you posted is not valid C anyway, there are no nesting functions in C.

Standard C and C++ do not support nested functions, but:
GCC supports nested functions in C, as a language extension.
The D language, which is C-related, has nested functions.
and CodeBlocks use GCC compiler only, hence you're are not getting any error.
For the question
about having two main() in C program
No you can't, this is how compiler interprets where to start executing the program. It will take one of the main as local.
Also,
you are not getting "hello" printed
because when compiler starts executing your first main() function, it takes the second main() as local, and because you haven't called the second main(), the string doesn't get printed.

No, there can't be two main functions in C, or in any other programming language. The code you posted is not a valid C program. It will NOT compile.

Yes, Having two main functions in C is possible. It could be done by messing up the compiler using macros/pre-defined functions. Here is the code snippet,
#include <stdio.h>
void main()
{
printf("Inside 1st main\n");
func1();
}
#define main func1
void main()
{
printf("Inside 2nd main\n");
}
Keep the preprocessor be as it is. Else you would get error.

Related

Function of main() in C programming

I am working in the C programming language. What is the function of main()? What is void main() and int main()?
It is the entry point of a C program. See here:
https://en.wikipedia.org/wiki/Entry_point#C_and_C++
Best answer of Brian-Bi:
void main() { ... } is wrong. If you're declaring main this way, stop. (Unless your code is running in a freestanding environment, in
which case it could theoretically be correct.)
main() { ... } is acceptable in C89; the return type, which is not specified, defaults to int. However, this is no longer allowed in
C99. Therefore...
int main() { ... } is the best way to write main if you don't care about the program arguments. If you care about program arguments,
you need to declare the argc and argv parameters too. You should
always define main in this way. Omitting the return type offers no
advantage in C89 and will break your code in C99.
What is the function of main()?
It is the entry point of your program. That's the first function which is executed when you run your program.
What is the difference between void main() and int main()?
The valid syntax for the main() function is:
int main(void)
It can also take arguments. See more here.
The second syntax is not valid:
void main(void)
That's because your main() should return the exit status of your program.

Why should I declare a function in C? [duplicate]

This question already has answers here:
Must declare function prototype in C? [duplicate]
(10 answers)
Closed 7 years ago.
I have two source files test1.c and test2.c.
In test1.c:
#include <stdio.h>
void main() {
checks(); }
In test2.c:
#include <stdio.h>
void checks(){
printf("This is a sample Text");
}
In this case I can successfully build and run this program.
So why should I use:
void checks();
To declare the function?
It seems perfectly fine now.
I am Using C99.
In your case, the check() function has a very simple prototype and the default prototype applied by the C compiler is to accept anything as argument and to return an int. It is probably what is done here (except that, as you do not store the result of the function it is optimized out without noticing it).
If you want to check my theory, try to write this (and it should work until it reaches the linking phase):
int result = check();
At the end, your code work because the linker finally find something that work to plug for the check() function (yet, it should still expect an int at some point).
In fact, the declaration of a function prototype is only useful in two cases:
The code of the function and the use of the function are in the same file.
When you use the function before its declaration (code source), then you need to tell the compiler what to expect when trying to statically type the function you are writing (the compiler read a source code file from top to bottom).
For example:
int bar (int a, int b, bool c);
int foo (int a, bool b) {
int result = bar (a, a, c);
...
}
int bar (int a, int b, bool c) {
...
}
The code of the function the use of the function are not in the same file.
Then, you usually get the definition of the function through a header file which collect all the information needed by the compiler to know how to statically type your code. The header file (*.h) contains all the prototypes of the functions of the module you are using. The implementation of the functions will come after at linking time.
Note that, I usually try to avoid the first case because it is really not logical. When you read a source code, you go from top to bottom, just as the compiler do, and you expect to find the function definition before its usage... So, it is much more logical to structure your code in a way that do not need to require such artifacts. In my humble opinion...

Why there is no error when passing command line arguments when declaring main as `int main(void)`?

Case 1:
void hello(void) {
//something
}
int main()
{
hello(1); //error
return 0;
}
Case 2:
int main(void) {
//something
return 0;
}
Execution:
./a.out something something //No error, Why?
Why there is no error? main will not be able to take any arguments. So why it is possible to provide arguments from the command line?
Because the C compiler and the command line interpreter (or whatever is used to invoke your program) are different things.
The C language allows various ways how main () could be declared.
The command line interpreter will make any arguments available to the program. If the program ignores them, that's none of its business.
The command line interpreter doesn't even know that you used C to compile your program. On my computer, the program could be written in C, C++, Objective-C, Objective-C++, Swift, Fortran, Ada, and so on. Each of these compilers may or may not do things to accept commands from the command line.
Not checking the specification nor compiled result, it will cause no error because the C runtime will get the arguments and pass them to main(), but this type of main() will ignore the passed arguments, and if it is caller's duty to clean up the memory (stack) used as the arguments, it will cause no problems just as getting some arguments and not using them in the code.
This code won't emit errors in C:
void hello(); // in C, the compiler won't check arguments
int main() {
hello(1); //no error
return 0;
}
void hello(void) {
//something
}
Because ./a.out something something is not directly calling your main function. THe main function is being called by the c runtime library. The command line arguments are placed in a region somewhere on the stack (very beginning) by the loader/c runtime. It is upto you if you want to access these arguments or not.
Plus as pointed out in one of the comments as well at least one command line argument is always passed anyways (the name of the program ./a.out to be precise) - so you must have wondered about an error in that case as well.
Recall that ISO C specifies the two possible signatures of main: int main(void) and int main(int, char *[]) and the equivalent versions thereof, like int main(int, char **) because of array-to-pointer decay. This is covered more in detail here.
This question can be answered by considering the opposite question: how does the C runtime know what main to call? C doesn't have overload resolution! This is explained here. Briefly, the others are pushed but not accessed because there's no indication from C to do that.
When you compile your program using gcc program_name.c, compiler will report any possible compile time warning or error. Since the command line arguments are not passed at the compile time, compiler is unaware of it and program just ignore that arguments.
In case of hello, compiler knows the prototype of this function and expects no argument to be passed in its call and hence reports error in case of any argument passed to it.

Issue with for loop in C

I was creating an int array and making all of its element 0 in C.
Using:
int arr[50],i;
for(i=0;i<50;i++){
arr[i]=0;
}
Which works fine if used inside a function or in main() like:
int main(){
int arr[50],i;
for(i=0;i<50;i++){
arr[i]=0;
}
return 0;
}
But something strange happens if we use the code outside of any function like:
#include <stdio.h>
int arr[50],i;
for(i=0;i<50;i++){
arr[i]=0;
}
int main()
{
printf("Hello World!");
return 0;
}
Gives error on compilation:
error: expected identifier or '(' before 'for'
for(i=0;i<50;i++){
^
So by that, is it that grammar of C doesn't support looping outside of a function?
If no, then why is this happening?
You're defining an anonymous block, which is not allowed (it needs to be predeceded by a function definition, otherwise, the compiler will never know when it will have to execute it).
In C, every line of code but variable declaration/initialization must lie within a function.
The only things that may appear at the top level of a translation unit are declarations or function definitions.
What you have here is confusion in programming paradigm. If I'm not mistaken (I may be! Just a guess...) you are familiar with python programming, which is written in an imperative paradigm. This means that within a file each line is read and performed top down, one by one. In such a paradigm your proposed code outside of a function would operate just fine.
Since you are writing in the C language you are writing in a procedural paradigm (or definitive paradigm). This means that code blocks are to be defined in procedures (functions) and can be referenced procedure to procedure. Calling one procedure launches the program, in C programming this one procedure is the main() procedure, recognized by name. Any code written outside of a procedure is syntactically incorrect (some exceptions I believe, macros and the like...).
Since correct syntax is the first requirement of program compilation in C (and all other procedural programming languages) the error occurs when attempting to compile and run this code.
I do hope this helps with a greater understanding! Paradigms are fun, they are the rules of using a certain language.
For executing a loop in C, it has to be inside a function. Otherwise compiler will not have any idea when to execute this piece of code. Most of the C compilers will give a compiler error in this case. Only variable initialisations/declarations can appear outside of a function
#include <stdio.h>
int arr[50],i;
/* This piece will not get executed
for(i=0;i<50;i++){
arr[i]=0;
}
*/
int main()
{
printf("Hello World!");
return 0;
}
It has nothing to do with looping in particular. All the statements must be put inside functions, otherwise... tell me, when do you think the code outside a function must be run? Have no idea? And the compiler too
You can initialize an array to 0 by just defining it with the first element initialized to zero.
int arr[50]={0};

Multiple definition of main()

Hi guys trying to use two main() and getting this error multiple definition of main(). I renamed my main functions then why is this error and also first defined here for my print().
header file:
#ifndef TOP_H_
#define TOP_H_
#include <stdio.h>
#include <string.h>
#define onemain main
#define twomain main
inline void print();
#endif /* TOP_H_ */
c file one:
#include "top.h"
void print();
int onemain()
{
print();
return 0;
}
void print()
{
printf("hello one");
}
c file two:
#include "top.h"
void print();
int twomain()
{
print();
return 0;
}
void print()
{
printf("hello two");
}
Basically any C (or even C++) program is a bunch of functions calling each other.
To begin a program execution, you have to pick one of these functions and call it first.
By convention, this initial function is called main.
When you include several source files in a project, the IDE compiles them all, then calls the linker which looks for one single function called main and generates an executable file that will call it.
If, for any reason, you defined two "main" functions inside all these files, the linker will warn you that it cannot choose on its own which one you intended to be the starting point of your program.
The macro substitution of onemain and twomain occurs before the compiler proper sees the program, so that doesn't make a difference. The functions are both named main.
C++ allows different functions with the same name, but does not allow two definitions of the exact same function signature. There would be no way to form a function call expression that would reach either overload. Additionally, the functions are the same entity, and one thing cannot have two definitions.
In addition, in C++ main cannot be overloaded, because the program is supposed to start when the unique main function is called, and any given system detects what format of main the particular program uses, out of a variety of allowed formats. (This auto-detection feature also applies to C.)
But you are not asking about C++; in C, without function overloading, there are no redefinitions of the same name, even for different signatures. Each name of extern linkage in C uniquely identifies an entity, so you cannot have two.
It's unclear what you want the resulting program to do. Most likely you need to build two separate programs.
I don't get what you ask - your error messages are quite clear:
You have 2 definitions of print(), which will collide. Remove one.
You as well have 2 definitions of main() - your #defines will replace your onemain and twomain functions, naming them effectively as main.
You overrode the built in print, about main, try imagining a car with two steering wheels ... it wont work ...
Your C program has two have a least one main, so the computer knows where the program starts.
If you have 2 files with two main function, then you have two different programs.
It's not possible for a C program to have more than one main() in it. Also, main() should be declared as an int and return an integer value (usually 0).

Resources