Search code examples
c++cmemorytypesallocation

Memory waste? If main() should only return 0 or 1, why is main declared with int and not short int or even char?


For example:

#include <stdio.h> 
int main (void)                         /* Why int and not short int? - Waste of Memory */ 
{
     printf("Hello World!");
     return 0; 
}

Why main() is conventional defined with int type, which allocates 4 bytes in memory on 32-bit, if it usually returns only 0 or 1, while other types such as short int (2 bytes,32-bit) or even char (1 byte,32-bit) would be more memory saving?

It is wasting memory space.

NOTE: The question is not a duplicate of the thread given; its answers only correspond to the return value itself but not its datatype at explicit focus.

The Question is for C and C++. If the answers between those alter, share your wisdom with the mention of the context of which language in particular is focused.


Solution

  • 1st: Alone your assumption/statement if it usually returns only 0 or 1 is wrong.

    Usually the return code is expected to be 0 if no error occurred but otherwise it can return any number to represent different errors. And most (at least command line programs) do so. Many programs also output negative numbers.

    However there are a few common used codes https://www.tldp.org/LDP/abs/html/exitcodes.html also here another SO member points to a unix header that contains some codes https://stackoverflow.com/a/24121322/2331592

    So after all it is not just a C or C++ type thing but also has historical reasons how most operating systems work and expect the programs to behave and since that the languages have to support that and so at least C like languages do that by using an int main(...).

    2nd: your conclusion It is wasting memory space is wrong.

    1. Using an int in comparison to a shorter type does not involve any waste. Memory is usually handled in word-size (that that mean may depend from your architecture) anyway
    2. working with sub-word-types involves computation overheand on some architecture (read: load, word, mask out unrelated bits; store: load memory, mask out variable bits, or them with the new value, write the word back)
    3. the memory is not wasted unless you use it. if you write return 0; no memory is ever used at this point. if you return myMemorySaving8bitVar; you only have 1 byte used (most probable on the stack (if not optimized out at all))