Похожие чаты

Can you check whether I've understood assert() correctly? For example: if (x

< 0)
{
std::cerr << "error message";
std::exit(1);
}


assert(x >= 0 && "error message");


Are these two equivalent?

11 ответов

9 просмотров

iirc assert only displays this message with abort instead of exit and it’s better for some cases

Sahand-🏔️ Автор вопроса
Igor
iirc assert only displays this message with abort ...

Yeah assert calls abort and abnormal termination while exit() does the normal termination. But I didn't mean this. I thought I couldn't understand the use of assert, then I googled it and read some about it in StackOverflow. They said "it's used in debugging to make debugging easier for programmers especially for bigger projects. So then we can get rid of writing printf() (or cout and cerr) for debugging (also the NDEBUG macro can be useful)" Now I find both ways (using exit()) and using assert sort of the same for debugging. Here only stopping and terminating the program is important.

Sahand 🏔️
Yeah assert calls abort and abnormal termination w...

You are confusing three different things : logging, exceptions and assertions. Asserts are used during development time for testing conditions that must be true no matter what. If they are false then it is a programming error. This could be used for testing preconditions, post conditions and invariants. In short you don't expect to recover from such errors and would rather see them fixed in the code. So though this happens at runtime, you won't use exceptions for this. These are mostly developer errors and the developer has to fix the code. Logging using cout, cerr or a logging library helps more with tracing/debugging an issue after it has occured. Assertions don't replace logging like you said earlier. They are two different use cases. Assertions and Exceptions tell us that something bad happened. Logging will help tell us why they happened. Exceptions can be used for all those cases where the error came from the environment rather (in some cases an exception can be caused because of a code issue as well and in such cases the logging you did will help you fix the correct code if at all it needs fixing. It is not possible to test such cases using assertions for ex the issue could have arisen from code changes in another vertical). For ex invalid user input, file not found, network connection error etc etc. These are errors that you can try recovering from. You throw an exception to indicate that such an error has occurred and the part of your program that catches this exception can hope to recover from it if possible. If it is not possible to recover you can still inform the user and gracefully shutdown (exit vs abort) As to when you should use abort and when you should use exit - you generally use abort for two reasons: 1) When your program is in a very bad situation and trying to run anything might further corrupt the environment. In such cases you don't want destructors of static lifetime objects to be called or exit handler functions (registered using atexit) to be called. You want a shutdown as soon as possible without doing much. 2) When you want a core dump (if they are enabled) to analyse what went wrong. There are some conditions that you may not expect to happen at runtime and in case they happen you may want to understand why they did. For such cases, you may want a core dump file to debug the issue. Use abort in such cases. For other cases, where you know why something unfortunate happened at runtime and you just want to shutdown gracefully, you just call exit.

Sahand-🏔️ Автор вопроса
Madhu
You are confusing three different things : logging...

What about this one For example, max_size() for std::vector is 3738472847928 but for mine is 5000000, a very smaller amount. So here I should do the exception handling by throwing 'bad_alloc' ?

Sahand 🏔️
What about this one For example, max_size() for s...

I don't understand your question. Do you want to know what you should do when a user tried to push back more elements than what the vector's max_size allows?

Sahand 🏔️
What about this one For example, max_size() for s...

I don't understand what you mean by max_size is 3738472847928 either. The max_size depends on the elements you store in the vector. The max_size for a vector<bool> may be different from max_size for vector<A> where A is a class you designed

Sahand-🏔️ Автор вопроса
Sahand 🏔️
Assume that it's an int vector

Answer the first question I asked

Sahand-🏔️ Автор вопроса
Sahand 🏔️
Yep

A vector's max_size is typically determined using the size of the virtual memory on that system (not necessarily true since an implementation can query the available memory and decide on some value that it thinks is feasible). If you reach the system limits then the OS will step in and terminate your process or there will be thrashing all around with so much swapping that the system might even hang with nothing progressing. These are situations that you don't typically handle in your code Ideally if you have a limit on the maximum number of elements that a vector can store (assuming this limit is far lower than what the theoretical maximum is), then you should throw an exception when the user attempts to exceed this size. This is not a code issue but an environmental issue like I mentioned in my first post. The code catching this exception may then inform the user that he has exceeded the max number of elements he is allowed to store and may also give him an option to delete some elements to free up space. What you do depends entirely on your use case.

Sahand-🏔️ Автор вопроса

Похожие вопросы

Обсуждают сегодня

Если у меня есть такой класс: Object = {} function Object:new(a_name, a_transform, a_color, a_mesh, a_material, a_shader, a_textures) local private = {} private.n...
Cuarno Vile
4
А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
62
Is Kadena onto something special? No one really knows. Good luck!
Bright Uncle Stephen EqualBet
40
At which price point will BCH, an ASIC mined coin, be succeptible to reorg attacks because of low hashrate? $10? $1? $0.1? $0.01?
Kishniev
18
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
Гайз, кто-нибудь пробовал запустить probe-rs под камень, которого нет в probe-rs? Мб есть какой-нибудь пример у кого... Через target-gen попробовал сгенерировать chip-descript...
Максим Смирнов
2
зачем же переименовывать ? чтобы кол-во участников возросло или вдруг IBM от этого снова на свифте начнет кодить ? Я не понимаю что страшного в том что свифт гавно, если это т...
Oleh Nerzh
10
I hodl ocean for a long time. Is there new development that I should read?
A33
12
Is there an article I can read for more information?
Lobaka
10
здравствуйте. совершаю вот такую вещь: strcpy(line, (char)current_number); где current number — неподписанный шорт, line — массив чаров. ругань следующая: main.c:29:30: error...
Roberto's Ширгозиев
13
Карта сайта