I've been programming in C++ for quite some time now and I know all functions must return a value.. but can someone tell me WHY we return 0?

I mean it compiles even when I don't put return 0.. and the program executes fine.. I can see in some functions we'd return a variable or a value.. but for int main() why do we always have to write return 0? Someone told me its the new standard that we don't have to type it anymore but I'm so used to return 0 that I can't not type it. I also heard its because when a function returns a value other than 0, it means something is wrong and the operating system can check the value it returned and check for memory leaks or something..

what if I returned 256? it still works.. :c

also can someone explain when i use unsigned variables?? I never use them unless a function on MSDN requires it.. so is there any use of them other than passing them to functions as parameters? Oh and when do we use constants? I mean I can just use a float or integer instead of const int or const float.. just don't change the value right? When do we use constants :S

I saw someone do this:

const float PI = 3.14159265f;
const float DEGREE_TO_RADIAN_FACTOR = 0.0174532925f;

can someone explain why there is an "f" at the end of the values??

Thanks in advance.

Recommended Answers

All 5 Replies

>> for int main() why do we always have to write return 0?
Its optional in c++ but not in C. The reason is because the c++ standards say its optional. If you don't specify a return value then return 0 is assumed.

MS-Windows and *nix operating systems do nothing with the return value except pass it along to a program that may have caused the program to be executed. return value of 0 is traditionally means the program executed everything successfully. Any other return value means nothing to the os, but traditionally means an error of some sort and the exact error is up to the calling program to determine.

Regardless of the return value the operating system will clean up everything when the program terminates.

>>also can someone explain when i use unsigned variables?? I never use them unless a function on MSDN requires it.. so is there any use of them other than passing them to functions as parameters

Yes -- I use them as loop counters and other occasions when negative numbers are not needed. I believe that gives the compiler to better optimize the code.

The reason for constants is to let the compiler know that the variable will never be changed, so that the compiler can optimize the code better. In some cases the compiler may be able to discard the const altogether.

I've been programming in C++ for quite some time now and I know all functions must return a value.. but can someone tell me WHY we return 0?

I mean it compiles even when I don't put return 0.. and the program executes fine.. I can see in some functions we'd return a variable or a value.. but for int main() why do we always have to write return 0? Someone told me its the new standard that we don't have to type it anymore but I'm so used to return 0 that I can't not type it. I also heard its because when a function returns a value other than 0, it means something is wrong and the operating system can check the value it returned and check for memory leaks or something..

what if I returned 256? it still works.. :c

also can someone explain when i use unsigned variables?? I never use them unless a function on MSDN requires it.. so is there any use of them other than passing them to functions as parameters? Oh and when do we use constants? I mean I can just use a float or integer instead of const int or const float.. just don't change the value right? When do we use constants :S

I saw someone do this:

const float PI = 3.14159265f;
const float DEGREE_TO_RADIAN_FACTOR = 0.0174532925f;

can someone explain why there is an "f" at the end of the values??

Thanks in advance.

Yep.

but can someone tell me WHY we return 0

Returning an error code probably had it's uses historically but is much less relevant today, and don't ever use "void main" because it can cause problems when the program exits without returning a value back to the OS. There is a FAQ answer on Bjarne Stroustrup's website about void main.

I mean it compiles even when I don't put return 0..

That's because the compiler inserts "return 0;" for you automatically.

also can someone explain when i use unsigned variables??

Yep, when you need the greater positive range the unsigned variable will allow, you can google "overflow" and "underflow" of variables in C++ for some interesting info. A quick explanation is something along the lines of:

signed type:
-something to +something
unsigned type:
0 to +a_lot_larger_something

Oh and when do we use constants? I mean I can just use a float or integer instead of const int or const float.. just don't change the value right?

Yes, but there may be unseen optimization for constant types from the compiler. Also, it's just good style.

can someone explain why there is an "f" at the end of the values??

Yep that's to denote the floating point number is a "float" type instead of a double.

Double is written as: 0.0
Float is written as: 0.0f
Unsigned int is written as: 0u
Unsigned long is: 0ul
etc.

-edit-
Oh I almost forgot, appending the suffix may be useful in this scenario:

void Foo(int n){ }
void Foo(unsigned int n){ }

Foo(0);
Foo(0u);

>> what if I returned 256? it still works.. :c

Yes, it still works, but if program A was called by program B and program A worked and returned 256, program B, when control returned to it, would have no way of knowing that program B worked. Program A returns 0 for success and non-zero for failure not for its own purposes but for program B's purposes.

You can think of it like calling a function from within main.

// returns 0 for success, 1 for failure
int SortArray(int* array, unsigned int size)
{
    if(arrayOfStrings)
    {
        // NULL pointer error
        return 1;
    }

    // code to alphabetize the array
    return 0;
}


int main()
{
    int array[10];
    // fill in with random numbers
    if(SortArray(array, 10) != 0)
    {
        cout << "An error occurred.  Aborting.\n");
        exit(1);
    }

    // print the array out
    return 0; // success
}

Now change 11 to "return 256". The program no longer works.

Ditto if one program calls another.

Exit Status

By default in Linux if particular command is executed, it return two type of values which is used to see whether command is successful or not.

(1)If return value is zero (0), command is successful.
(2)If return value is nonzero , command is not successful or some sort of error executing command/shell script.

This value is know as Exit Status of that command.

To determine this exit Status we use $? variable of shell.

http://www.freeos.com/guides/oldlsst/getting.htm

Suppose I have program called "myProgram1" and "myProgram2" and I call it from a script and I want to abort if myProgram1 fails, but continue if myProgram1 succeeds

#!/bin/bash
myProgram1 || exit 1
myProgram2
exit $?

This will abort if myProgram1 returns anything but 0. If myProgram1 returns 256 on success, then myProgram2 won't execute because the shell script will abort prematurely.

The answers so far are very good and pretty complete, but I'd add a few things:

>>also can someone explain when i use unsigned variables??

Well, the only unsigned type you would really every use it unsigned int (or a similar type like uint64 and such). Unless you need an unsigned type of a specific number of bytes (e.g. for binary operations), then you typically only need the unsigned int type to describe some large size value (like an index or pointer). In that case, it is generally not even recommended to use "unsigned int", mostly by convention. The C++ standard defines a type called std::size_t which is preferred to describe array sizes or indices, which is the usual purpose of an "unsigned int".


>>Oh and when do we use constants? I mean I can just use a float or integer instead of const int or const float.. just don't change the value right?

"just don't change the value.." That's pretty weak. The same thinking would lead to declaring "hey guys, let's just not commit crimes, ok?" and then say that you don't need cops anymore. The compiler is the police service in the source code. Marking a variable as const makes sure that any intentional or non-intentional changes to the value will be caught by the compiler. It helps catch a classic typo like if(PI = my_angle) . This is often the main reason for using const, minimize the chance for erroneous code by giving the compiler the power to enforce the rules.

Far behind, another reason for using const is to be able to use the value in the definition of things that require compile-time constants. For instance, a static array, like int array[MAX_SIZE]; . Another case involves template arguments of integral type and other template-related definitions.

Finally, there could be some performance benefits to marking as const a variable that will never change. However, that's debatable. There is no real reason why it would enable optimizations that wouldn't be possible without the const qualifier. But, you might as well do it anyways.

unsigned variables are great when working with index values that may not be < 0.

Without unsigned

int index = <some value>;
if(!(index >= 0 && index < _myArray.size()))
{
  //oops we are out of bounds  
}

With unsigned

unsigned int index = <some value>;
if(!(index < _myArray.size()))  //Note, no need to check for ">=0"
{
  //oops we are out of bounds
}

Using unsigned variables when comparing with size_t values like vector::size(), list::size() will help you get rid of annoying compiler warnings like this one:

"WARNING: comparison between signed and unsigned integer expressions"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.