Assert expressions

C/C++ Forum

Each of my Vensim simulation modelling applications has a considerable number of C subprograms. These support the models. Each application also has large numbers of asserts. These have several contexts, such as

reti = fclose(file1); or refi = fopen_s(&file1, filnam,
"r");
assert(reti == 0); assert(refi != EOF);
or

retc = fgets(filnam, 30, file1); or refi = fscanf_s( file1, " %hd
\n", &nhold[nn1]);
assert(retc != NULL); assert(refi != EOF);

I did most of my work under Visual Studio 2008. Assert expressions were then apparently not a problem. Now I need to bring the work forward to VS 2017, where assert expressions are much more of a problem.

The above expressions use three assert forms. Perhaps there are additional forms. My question now is: which form of expression is correct in each type of case in which assert is used? The alternative is to correct each instance to which the VS 2017 compiler will object. Those will number in the high hundreds.

Thank you in advance for any light that you can shed on the applicable rules.

John Weldon
Canberra Australian Capital Territory

Tel: 61 2 6286 6728
Now I need to bring the work forward to VS 2017, where assert expressions are much more of a problem.
A problem how?

The above expressions use three assert forms.
What do you mean? I see just one: assert(x), where x is some boolean expression.

If you don't care about the asserts you can just compile in release, or even just define assert to be anything you want.
1
2
#undef assert
#define assert(...) 
The above expressions use three assert forms.
What do you mean by 'form'? I see four assert statements in your code, all of them essentially being the assert(bool).
Last edited on
I see lots of bad use of assert()

https://en.cppreference.com/w/cpp/error/assert
Asserts are used by programmers to verify the operation of the program.
You would put asserts() to check for things which 'must be true', for example:
1
2
3
4
5
6
7
void foo ( const char *str ) {
    if ( str ) {
    } else {
       // this shouldn't happen
       assert(str != nullptr );
    }
}

An assert(), when it triggers, either aborts the program, or drops into the debugger.


> refi = fopen_s(&file1, filnam, "r");
You don't use assert() to check for user errors.
Getting the filename wrong for example should be met with
- a prompt to try again
- a helpful error message.
Not a program abort with a cryptic error.

It gets worse.
When you compile the program in release mode, the asserts() are removed.
So now instead of aborting the program if the user gets the wrong filename, the program just carries on with bad data.
Topic archived. No new replies allowed.