How to pass arguments from other functions to main…

hi every one!

i have a question, how to pass arguments from other functions to main. i want to write a program like nano well not exactly like nano editor. I have a function f_read(char* filename[]), and fopen() get filename[1] as file name and *filename[2] as "r" read mode and rest of the code will read from a file.

I want is this char filename[] to main(int argc , char argv[])

how can i do that??

any help will be appreciated
closed account (28poGNh0)
Those functions do they belong to the same file as main functions is ?
You can't call main from another function. The C++ standard forbids it and if you did it would create recursion.

The arguments to main are intended for the operating system to pass arguments to your program from the command line used to initiate your program.

There's no reason you can't create another function and pass whatever arguments you like to that function.
I'm sure you can call main from other functions as long as main exists in the scope of the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdio>

void callback(int);

int main(int argc, char **argv) {
	printf("Argument name is %s\n", *argv);
	callback(argc);
	return 0;
}

void callback(int p) {
	char *cal[] = { "callback" };
	p ^ 2 ? main(-~p, cal) : 0;
	printf("%d\n", p);
}


But generally whenever you find yourself calling main, you have to rethink your approach to solving that problem. Calling main is never an option, the above example shows that it is possible but generally frowned upon.
Use a break statement if you are calling main to break out of a loop, use a return type if you want to get back to main from a function.
> But generally whenever you find yourself calling main,
> you have to rethink your approach to solving that problem.

Without exception, whenever you find yourself calling main() (which is at file scope), and the C++ program compiles cleanly, you do not have to think - just throw that particular compiler away.

The name main is not otherwise reserved; you could do something like this instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace nano
{
    int main( int argc, char* argv[] ) { /* ... */ return 0 ; }
}

int foo( int argc, char* argv[] )
{
    // modify or replace argc, argv as required

    // eg. argc = 2 ;
    // etc...

    return nano::main( argc, argv ) ;
}


int main( int argc, char* argv[] )
{
    return foo( argc, argv ) ;
}

Last edited on
Topic archived. No new replies allowed.