Question

I'm trying to set an invalid value to -1.. But I don't like magic numbers.. Anyone know where to find a set of common constants. I'm working in VS6 (ish).

I'm trying to read a file from across a network, and I need a bad value for the total file size,so I know if I got valid info on it.. 0 is a valid size so I can't use that.

Harper Shelby HIT THE NAIL ON THE HEAD.. Just a little thumb. He mentioned the win32 constants.. which is exactly what I was thinking about.. Now to find a link :)

Was it helpful?

Solution

#define BAD_VALUE -1

EDIT: the original question had no context. The revised question indicates you want an invalid file size and are thus looking for the win32 constants. Look at windows.h i think the constant you seek may be in windows.h or one of its sub-includes. grep your windows include directory ;-)

OTHER TIPS

If -1 is an invalid value for a return value in your system, you should define it internally:

const int INVALID_FOO = -1

unless C compatibility is needed, in which case

#define INVALID_FOO -1

would be preferred. If it's a standard MFC or Windows resource, use INVALID_HANDLE or one of the other Win32-defined constants.

You want to use your own magic number -1 disguised as a Windows constant. This is very misleading.

Suppose I happen to know that INVALID_HANDLE is 0. Is it OK to initialize my pointers with INVALID_HANDLE?

char *myMessage = INVALID_HANDLE;

How does this strike you?

In VS, Create a new windows console application project. Go into project settings and turn on browse support. Create a C++ file and add it to the project. Type:

#include <windows.h>
void main(void) {}

into the file. Compile it. Now type INVALID_FILE_SIZE into the file. Right click on it and goto definition of INVALID_FILE_SIZE. VS will open one of the many windows header files full of defined values. Enjoy.

First thing is you should be using an unsigned int for file size as a file size is never negative. Now an invalid file size is normally the max int so in the case of using a 32 bit unsigned int it would be 0xFFFFFFFF

i.e.

const unsigned int INVALID_FILESIZE = 0xFFFFFFFF;

Also if this is on windows, windows.h defines invalid file size all ready (INVALID_FILE_SIZE)

If you want to use constants used by WinApi, check out the WinError.h, WinUser.h and WinNT.h files.

It's generally accepted the 0 and 1 (positive & negative) are OK to use directly.

In fact, it'll probably make you code even more confusing to use a variable instead.

Update: OK, you updated your question after I wrote my answer. If you are using "-1" in an arithmetic way, then just "-1" is fine. If you are returning a error code (and the code just happens to be -1) then you should use a const.

 const int INVALID_VALUE = -1;
If bytes_read < 0
    // error
EndIf
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top