What's the differences between exit(0), exit(1) and exit(-1)?

Dani AI

Generated

— good question. and covered the basics (zero = success, non‑zero = error; prefer returning from main when you can). A few practical, platform‑aware points that often cause surprises:

Use the standard macros EXIT_SUCCESS and EXIT_FAILURE from <cstdlib> instead of magic numbers; they express intent and improve portability ().

How the host sees the numeric value is OS dependent. On POSIX systems only the low 8 bits are returned to the parent (status & 0377), so negative values wrap into 0–255 (for example, -1 becomes 255) (exit(3)). Windows treats the process exit code as a 32‑bit value at the OS level (see ExitProcess) so different truncation/interpretation rules apply (ExitProcess). Because shells and parent processes often expect 0–255, prefer small non‑negative codes for scriptable programs.

Behavioral differences matter: std::exit calls functions registered with std::atexit and flushes/close C streams, but it does not perform normal stack unwinding for local objects; returning from main ensures local automatic objects are destroyed. For immediate termination without atexit handlers or flushing, use std::_Exit; for abnormal termination that raises SIGABRT consider std::abort (std::exit, std::_Exit).

Practical rules: prefer return from main when possible; use EXIT_SUCCESS/EXIT_FAILURE; document any non‑zero codes your program uses; avoid negative codes if consumers are POSIX shells.

Recommended Answers

All 5 Replies

The paramarater is the value that the program will return to the operating system so that other programs can use it for some purpose. The value 0 traditionally means the program exits normally without error. Any other value would mean the program encountered some kind of error. The value of the parameter to exit() can be anything you want, its not limited to the three that you posted.

Exit(0) , is commonly used as a successful exit message. Usually, you don't use it, use instead Return 0; Exit(1) Is used to reference some kind of abnormal program termination.

>>Usually, you don't use it, use instead Return 0;

Unless, of course, exit() is used outside main().

Point granted ;)

Thanks for the info.

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.