Compiler warning: Comparison of signed and unsigned types

In some parts of my code, the compiler emits a warning regarding the signedness of integers. The warnings look like this, for instance:
warning: comparison of integer expressions of different signedness: ‘size_t’ {aka ‘long unsigned int’} and ‘int’ [-Wsign-compare]
assert(strlen(word) == k); where k is an int. I have previously asserted that k >= 0.
Will this warning create problems in the evaluation tests, especially regarding the points for the style? If I could, I would make k unsigned, of course, but we are not supposed to change existing signatures.

No, this should not cause any problems as far as I am aware. It is a compiler warning, and unless the style tests complain, it can be ignored.

What actually happens here is that when you compare integers of different signedness (as well as for other binary operations), they are both converted to unsigned integers implicitly.
This would lead to potentially unexpected results when one value is negative.

Like you said, you are not allowed to change existing signatures. If you want to get rid of the warning, you could, however, use a local variable of type unsigned int to store the value of k. Making the type cast explicit ((unsigned) k) should also work.

1 Like

A word of warning: Using assert for any kind of business logic is a very bad style. An assert is a tool for the programmer that some thing never happens. In debug builds, these are usually enabled, so that you can catch bugs in your program. In production builds, one usually turns them off, so that the program is faster.

This means that assert should only be used to document local invariants that you yourself establish in your code. For example, if there is some method written by you, for you, you can assert that the input never NULL, since you also can guarantee that it is never invoked with NULL.

If you instead use assert to check whether user input is sane, you may run into problems. The optimizer may simply remove your asserts, and then invalid user input will trigger undefined behavior.

To quote the manpage of assert:

If the macro NDEBUG is defined at the moment <assert.h> was last included, the macro assert() generates no code, and hence does nothing at all.

So if you want to actually catch bad input, always explicitly call abort().

1 Like