Why is it bad to type void main () in C ++

Possible duplicate:
Difference between void main and int main?

Why

void main() { //return void } 

badly?

The other day I typed this, and someone pointed out to me that it was wrong to do this. I was so embarrassed. I wrote this for a while, I know that this is not a C ++ standard, but the compiler does not give any warnings. Why is this wrong?

+4
source share
5 answers

Since the compiler you are using does not throw errors, this does not mean that other compilers will not. You know, this is not a standard, because ...

+3
source

Since each program should indicate to other programs whether it was successful or there was some kind of error, and you cannot do this if your main function returns nothing.

In addition, the standard says that main should return int.

+2
source

This is incorrect because it is not standard. One compiler could accept this, another could complain, and pedantic believers would still burn your ass at the stake.

+2
source

Wrong, because the standard (at least C ++ 03) states that main should return int (for hosted environments, i.e. stand-alone environments such as embedded systems can do whatever they need). From 3.6.1 Main function, paragraph 2 :

Implementation should not predetermine the main function. This function should not be overloaded. It must have a return type of int, but otherwise its type is determined by the implementation.

All implementations must allow both of the following definitions of main: int main() { /* ... */ } and int main(int argc, char* argv[]) { /* ... */ } .

If you value portability at all (and you need it), you should write code that conforms to the standard as much as practicable.

Undefined behavior like:

 x = x++ + --x; 

may work (for any definition of "work" you have) in some circumstances, this does not make it a good idea :-)

+1
source

This is non-standard.

i.e. you do not write "C ++" (as it was intended) when you write this. It may look like C ++, but you are not following the rules, so you are not really writing C ++.

In most cases, its result is undefined.

Unlike other languages, such as C ++ or C #, where "bad" behavior causes errors, C ++ resolves something when an erroneous construct is used. Thus, you cannot depend on the compiler doing the β€œright” thing, because it can do it once, but not another.

In general, you want to avoid undefined behavior, so you shouldn't.

+1
source

Source: https://habr.com/ru/post/1403287/


All Articles