Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use asserts in C?

Tags:

c

I am writing a function in C. As a matter of style, when is it good to use assert compared to returning an error code. Lets say the function is dividing two numbers. Should I assert the divisor be non-zero or should I return an error code? Please give more examples, if you can, to make the distinction clear.

like image 612
Bruce Avatar asked Nov 13 '11 19:11

Bruce


People also ask

When should asserts be used?

Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen. For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.

Why we use assert in C?

In the C Programming Language, assert is a macro that is designed to be used like a function. It checks the value of an expression that we expect to be true under normal circumstances. If expression is a nonzero value, the assert macro does nothing.

What are asserts used for?

Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state a code expects before it starts running or the state after it finishes running. Unlike normal exception/error handling, assertions are generally disabled at run-time. Arguments to private methods.

Should I use asserts in production code?

JUnit assertions are intended to be used in test code, but not in production code. Using JUnit assertions outside of test scope may be confusing.


1 Answers

assert aborts the process, but is turned into a no-op when the program is compiled with -DNDEBUG, so it's a rather crude debugging tool and nothing more than that. You should only use assert to check for situations that "can't happen", e.g. that violate the invariants or postconditions of an algorithm, but probably not for input validation (certainly not in libraries). When detecting invalid input from clients, be friendly and return an error code.

An example use of assert could be: you've implemented an incredibly smart sorting algorithm and you want to check whether it really sorts. Since the sorting function is supposed to "just work" and therefore doesn't return a value, you can't add error returns without changing the API.

void sort(int *a, size_t n) {     recursive_super_duper_sort(a, 0, n);     assert(is_sorted(a, n)); }  static bool is_sorted(int const *a, size_t n) {     for (size_t i=0; i<n-1; i++)         if (a[i] > a[i+1])             return false;      return true; } 

In the long run, you'd really want a proper unit testing framework for this kind of thing instead of assert, but it's useful as a temporary debugging tool.

like image 86
Fred Foo Avatar answered Oct 29 '22 02:10

Fred Foo