• C

Initialization to invalid value

Consider all 1's to be an invalid value in our implementation.

For initializing the signed quantities to all 1's, we can use the following macro
                #define INVAILD_VAL    (~0)
It will work for irrespective of the size of the datatype during initialization.

But during comparison, it fails....

         unsigned char var = 0xff;

        if(var == (~0))
                printf("Not Equal");

Above example prints 'Not Equal'. However, if datatype of 'var' is changed to unsigned long it print equal.

can you suggest some generic mechanism to check for invalid value for unsigned quantities irrespective of their size.

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kent OlsenData Warehouse Architect / DBACommented:
Hi VivekGupta22,

You can do it just as you've tried, with a modification or two.

If you know the data length, it's easy.

#define INVALID8 0xFF
#define INVALID16 0xFFFF

If you can live with your data being "signed", then:

if (var == -1)

is always a good test.

if you know the length of your variable, you can always define it larger than the expected type so that you can declare a valid as absolutely an error flag.  In a 32-bit world where you need an int:


_int64 var;

if (INVALID == var)
  /* do something about INVALID */

This test will always work because it's a 33 bit value that can never be generated in a 32-bit variable.

Good Luck!
if (~var == 0)

Or, more compactly:

if (!~var)

Sorry, the solution I posted doesn't work.  The following works, but is not as pretty, because it requires you to repeat the type:

if((unsigned char)~var == 0)


if(!(unsigned char)~var)


INTRODUCING: WatchGuard's New MFA Solution

WatchGuard is proud to announce the launch of AuthPoint, a powerful, yet simple, Cloud-based MFA service designed to eliminate the vulnerabilities that put your data, systems, and users at risk.

Here's another way that is truly generic, though not beautiful:

#define isValid(var) isValidFunction(&var, sizeof var)

int isValidFunction(const void * pVar, int size)
      int index;
      const char* p = pVar;
      for (index = 0; index < size; ++index)
            if (p[index] != (char)~0)
                  return 1;
      return 0;
This is an obscure one. The problem is with the:

      unsigned char var = 0xff;

                if(var == INVALID_VAL)

INVALID_VAL evaluates to ~0 or 0xffff in my 16bit compiler, but val is a char variable and so evaluates to 0xff.

This should only happen with unsigned char. With char, the top bit is sign-extended into the upper byte before comparison.

All this points up a general point. You cannot define a general invalid value for all types. Not even for the base types.

Long long time ago
When 'puters cost lots of dough
A guy in Detroit had a flash

"tacked onto every single word in core
we can add an extra bit or more...
And propagte this into cache"

One bit can mean this word's a loser
It hasnt ever been set by the user
Another bit could mean read-only store

Sure, it will cost an extra dime or two
But think of the programmers whoopde-do
When it catches errors by the score

So Burroughs did implement this
And many hackers did their mainframe kiss
As they saved eons of debug time

But in recent years this has faded away
As marketing drones had their say
(And there is no lower slime.)

So we've got computers that run real fast
And memories that are goggone vast
At least compared to years of yore.

But were wasting tons of cash
Tracking down unset bits unabashed
That have never been initialized

And the hardware is no darn help
With unset garbage it doesnt yelp
And so it goes, on and on

As long as marketing slime  rules
The programmers will look like huge fools
Having no tools to catch big bugs

And projects will take forever to fix
unset vars from XP to Unix
Will go undetected and cause big bombs.

Until hackers rise up and demand their right
to have harware to detect bugs on sight
and tell us what's not been ever set

Then the programs will behave
and coders will not look like knaves
that stumble thru the total dark

And BSOD's be in the history books
hackers won't get many dirty looks
and a new age will then appear

Coders will get off by noon
and be fed honey from a spoon
by super-models at their beck

And market droids will slog away
polishing my shoes night and day
eventually to die and go to deepest heck.

And no more "seg fault" in system log
No pages do #NAN#'s clog
And no more beep and reboots quick.

For that I wish, and a tad more
as I stare at screens galore
looking for that unset thing or place.

Until then, at hex dumps I'll peer
and I'll consume too much beer
in this never-ending chase.

-- grg99

Kent OlsenData Warehouse Architect / DBACommented:

>and I'll consume too much beer

Is this even possible?

>>and I'll consume too much beer
>Is this even possible?

Sure, any amount of beer is too much beer for us vodka consumers. :)
I respectfully object.   VivekGupta22 asked for a "generic mechanism to check for invalid value for unsigned quantities irrespective of their size."  Kent's first and third answers don't satisfy the "generic, irrespective of size" requirement, and his second answer doesn't satisfy the "unsigned" requirement.  They are perfectly valid answers, they just don't solve the problem that was posed.

Also, grg99 deserves some points for sheer creative brilliance.
> Did grg99 really write that up just for this question?

Beats me.  I wouldn't be surprised.  Maybe he will inform us.

> Should the answer be "there is no general mechanism to check for an invalid value for unsigned quantities irrespective of their size"???

I think that's true if by "mechanism," you mean a reasonably simple, standard, portable expression.  That was Paul's answer.  If a "mechanism" can be a function, I think my last answer works.

> I vaguely remember there being some oddity in the C language specification for promotion of unsigned values in expressions, but I can't find it. If your (efn's) response had been:

> if  ( ~var == '\0' )

> would it have avoided the problem you subsequently tried to patch over with casts?

No, I don't think so.  I think the problem is that when you compare values of different sizes, the smaller will be promoted to the size of the larger, and unsigned promotion adds zero bits on the left, so you would need an invalid value that compares equal to all of 0xff, 0xffff, and 0xffffffff.  Also, the complement operator will promote to int.  There may be an ingenious way to do it, but if so, I don't think it has appeared on this page...not yet, anyway.
IMHO. Since we all tried and, in our own ways failed to provide what the asker wanted (because, as I pointed out, it was impossible) I'd go for giving the points to grg99 as his failure to solve the problem travelled paths as yet untrodden.

PAQed with no points refunded (of 125)

Community Support Moderator

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.