简体   繁体   中英

Returing string from main function in c++

Is there any way to return string from main function in c++? i am mentioning the sample program below

string main(int argv, char* argc[])
{
  .
  .
  return "sucess";
}

The standard says:

3.6.1 Main function [basic.start.main]

2/ 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

as the type of main. [...]

So no, you have to return an int.

From your comments on your post, you seem to want to simply output a string on the standard output, then you can do:

#include <iostream>
int main()
{
    std::cout << "Success" << std::endl;
    // No need for return 0; it is implicit in C++
}

As Kerrek SB said in the comments, the return 0; is implicit in C++ (standard § 3.6.1 /5 ):

[...] If control reaches the end of main without encountering a return statement, the effect is that of executing

 return 0; 

Nope, It's not standard compliant. You have to return an int in order to show to the caller how the program exited (good, with an error ?).

And why would you return a string ?

No you can't, you must always return an int . Thinking more deeply, a string would be difficult for a shell program to deal with: when would the memory be released, what kind of string would be returned &c.)

However you can write to standard output or standard error using std::cout or std::cerr . That's the normal thing to do when you want a console application to output string-like data.

Typically, you then rely on your OS shell to direct the standard output of your program to the input of another one (unix uses the pipe | for that).

No, you can't return string from main in c++, cause return value from main function is process return code (0 if success, not 0 if process failed). So OS is waiting proper signal of ending from your app.

You probably mean to write to the standard output :

#include <cstdio>

int main()
{
    // ...

    std::puts("success");

}   // no "return", success is implicit in C++

That's one of the standard way for processes to communicate data, and many tools are geared for being used in this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM