Sign in to follow this  

Question about the main function

This topic is 3860 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Which version is better? My textbook writes the main function as:
#include <iostream>
using namespace std;//Same ? applies to namespace
int main(){
....
return 0;
}
I have seen other books and tutorials use:
void main(some arguments){}

Just curious which is best to use? I have gotten use to the first method, will this pose a problem as I go on to Data Structures and the rest?

Share this post


Link to post
Share on other sites
If you don't care about the command line, use

int main();

If you want to have parameters passed to your program, use

int main(int argc, char** argv);

In most cases the first version works just fine.

Share this post


Link to post
Share on other sites
Basically, it comes down to whether or not you want your program to accept "command line arguments". If you declare...

int main() { ... }

You're indicating that you have no use for arguments coming into the app. If you do want to be able to use arguments, then indicate those in the function header.

An example might be something like running "unzip.exe" from the command line. Not useful unless you can also indicate what you want unzipped, such as "unzip.exe myfile.zip". That's where those passed in arguments would be used.

{Edit}I was too slow... lol what nmi said is perfect :) {/Edit}
Hope this helps,
Scorp

Share this post


Link to post
Share on other sites
Yes it did thanx. How do you delete this thread being that my ? has been answered!!
Oh wait
What about the namespace thing? Declaring it above the main or or using the std:: ...

Isn't it easier to just declare outside the main so that all functions have access to it?

Share this post


Link to post
Share on other sites
After a program is executed and finishes it will return to the OS a return code. This is defined by what main(...) returns. So if main were to return an int, it could exit with return code -1, 0, n. If main were to return void, then I believe the program just returns 0.

Return codes were a useful way of debugging and checking the execution of a command line program under a unix environment, but given todays applications this is more of a history lesson than something practical. I know you can check for them under windows, but I just don't know how.

Hope I didn't make this too complicated but in C++ you can build frameworks to be encapsulated into a namespace. This is useful for identifying what it is you really want to work with. For example, in the package Gdk we have two classes that are in different sub-packages but share the same name. To specify which DateTime we want to use, we have to use the 'using class' deceleration.

using namespace Gdk;
using namespace Gdk::Sql;

// Uncomment one to specify which DateTime we want to use by default.
// using Gdk::DateTime;
// using Gdk::Sql::DateTime;

DateTime myTime; // C++ has no idea which DateTime to use.

// or

Gdk::DateTime myDateTime;

Share this post


Link to post
Share on other sites
Yep, what MrRage said.

If it helps to have a direct example from what MrRage posted, consider this. Let's say for some reason I don't like the provided library of functions that have been placed into the "std" namespace, so I create my own functions and place them into my own namespace, say... "myLib". In my own version of this library, I also use some of those key function names, such as cin and cout. Now, I could actually mix and match between both versions of cout, by directly using the namespace with it. For example std::cout would call cout in the "std" library, whereas myLib::cout would call mine.

That being said, as long as you know ahead of time that you'll never use a duplicated function name in your program from a different namespace, putting the "using namespace" global is fine, and saves some typing. If you get to where you could have multiple functions with the same name, but in different namespaces, such as what MrRage said, putting a global "using namespace" would no longer work, as the compiler wouldn't know from which namespace your calling the function from.

Scorp

Share this post


Link to post
Share on other sites
Just as an aside, the C++ specification says that main, and main alone, will return zero by default. So the following is a perfectly functioning program:
int main()
{
}

Share this post


Link to post
Share on other sites
Great!!
I had another question or two. What is the ternary operator look like and what is its syntax and use? Is this the symbol ->, if not, what symbol is this?
I've seen it used like: aChar[25] -> strlen(aChar)

Thanks!!

Share this post


Link to post
Share on other sites
That's... I have no idea what you're talking about. A ternary operator is an operator that takes three things. There's only one in C++, and it looks like this:

expr1 ? expr2 : expr3

If expr1 evaluates to true, it'll execute expr2, if not, it'll execute expr3.

The -> operator is a binary operator, which is equivalent of (*pointer).identifier. For example:

struct Me
{
void speak() { std::cout << "Hi!" << std::endl; }
};

int main()
{
Me * me = new Me;
me->speak(); // same as (*me).speak()
}


Finally, I doubt you've actually seen it used like that before, because even though I think it's possible, it's the most screwed up thing I've ever seen. :D. You'd have to write your own class and have all the implicit casts and it'd be a right mess.

I hope this clears up any confusion.

Share this post


Link to post
Share on other sites
What you saw was most likely an excerpt from another language, where the -> operator assigns one object to the other. Although in C++ the -> operator is only syntactic sugar for the member-selection operator applied to a pointer, and you can thus redefine the meaning of the operator for UDT, the expression you posted doesn't make sense in a C++ environment (it is possible however, because we don't know anything about the type of aChar).

_goats definition of the only ternary operator in C++ is what you were looking for I guess.

Share this post


Link to post
Share on other sites
Quote:
Original post by bluefox25
Yes it did thanx. How do you delete this thread being that my ? has been answered!!

Why would you want to do that? Shouldn't others be able to profit from the answer too? (And what if you'd only gotten part of the answer so far, and later on, someone else might pop in to explain in more depth? That's hard to do if the thread is deleted)
In general, don't delete threads, and don't put [solved] in the title.
Quote:

What about the namespace thing? Declaring it above the main or or using the std:: ...

Isn't it easier to just declare outside the main so that all functions have access to it?


Easier, yes. In the same way that it's easier to just cram everything inside the main function, instead of writing different functions for different things.
In other words, yes, you save a little bit of typing initially, but it will come back and bite you in the long run.

If you do this:
using namespace std;

you're pulling *everything* from the std namespace out into the global one. That might be fine for a while, but what if, later on, you start using a math library which has a class called.... vector? Of course, you also make a
using namespace MyMathLib;
,
so how does the compiler know whether you refer to std::vector or MyMathLib::vector in your code?
Or you use some other library that declares a string class. Again, how can the compiler tell them apart if you pulled both into the global namespace?

So in general, it's better to not use 'using' statements like this.
It's better to just type the 5 extra characters to specify that you want the std::vector specifically.

Share this post


Link to post
Share on other sites
Quote:
Original post by bluefox25
Which version is better?


int main() // legal
int main( int argc, char ** argv ) // legal
void main( ... ) // ILLEGAL

Quote:
Original post by bluefox25
How do you delete this thread being that my ? has been answered!!

You don't. Now others googling this thread with the same question can have their own answered by proxy.

Quote:
Isn't it easier to just declare outside the main so that all functions have access to it?


Yes and no. First rule of "using namespace _____;" statements:
Never do it in a header file.

Namespaces were invented to avoid namespace collisions, and explicitly specifying the "std::..." namespace can avoid ambiguities or just help keep things clearer. For example, you wouldn't want to confuse std::vector, the container, and somemathlibrary::vector, the mathematical construct. (EDIT: Looks like Spoonbender beat me to the punch here, but I'll leave my further explainations here)

The problem with it in headers is that it "leaks". Consider a source file with two #includes:

#include "something_that_does_using_namespace_std.hpp"
#include "something_that_does_using_namespace_mathlib.hpp"

// both std and somemathlibrary have been "imported", leading to
// ambiguities even if we now specify our own using statements:
using namespace somemathlibrary;

vector a(1,2), b(3,4), c( a + b ); //ERROR: Ambiguous -- did you mean std::vector or somemathlibrary::vector ?


I avoid "using namespace ____;" statements in the global scope for the most part. I'm in the habit of typing std:: for most standard library components, the extra 5 characters here and there is small enough I don't even notice it. That said, if I have a piece of code that uses one namespace heavily, I'll almost always put it inside a specific scope (which is the one time it's actually semi-kosher in headers too):

#include <iostream>
#include <string>
#include <vector>
#include <somemathlib.hpp>

int main() {
using namespace std; //inside of main(), this will only last for main().

cout << "Hello world!" << endl;
vector<int> numbers; //OK: Unambiguous
numbers.push_back( 42 );
}

string a; //ERROR: using namespace std; only applied to that function.
std::string b; //OK

void some_other_function() {
using namespace somemmathlib;

vector a(1,2), b(3,4); //OK: Unambiguous (not affected by earlier "using namespace std;")
vector c = a + b;
}





For maximum clarity, I usually only do "using namespace _____;" statements for one namespace if I'm doing any at all. If I need to juggle multiple namespaces, I'll tend to prefer namespace aliases:

namespace example = std;
example::cout << "..." << example::endl;


Of course, this only helps if the alias is smaller than the original namespace name.

Share this post


Link to post
Share on other sites
It should be noted that you don't have to put using statements globally. FOr instance, this is allowed:

#include <iostream>

int main()
{
using namespace std;
cout << "Hello world!";
}


And that way you limit the scope of what is put into the global namespace for that one function. If you plan on using a lot of stuff in the namespace in a function then that might be a good compromise.

Share this post


Link to post
Share on other sites
Quote:
Original post by bluefox25
The binary operator can only be used with a pointer though right?


There are many binary operators. It just means "taking two arguments", and all kinds of things do that - for example, all the comparisons ('<', '==', etc.), and many mathematical operators ('+', '*', '/'). (Note that '-' can be either a binary operator - subtraction - or a unary one - negation. Naturally, "unary" means "taking one argument". [smile]). There is no such thing as *the* binary operator.

The operator '->' - sometimes called the "arrow" operator - requires a pointer to a struct or class on the left hand side, and the name of a member of that struct or class on the right hand side.

As for '?:', it's called *the* ternary operator because (a) it happens to be the only one in C++ which is ternary, and (b) noone seems to have a better name for it. [smile]




Otherwise, just listen to MaulingMonkey, ok?

Share this post


Link to post
Share on other sites

This topic is 3860 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this