Defning SIZE_MAX

O

ozbear

In another thread related to size_t and SIZE_MAX, a #define
was suggested for SIZE_MAX where is it not predefined.

The #define was:

#define MY_SIZE_MAX ((size_t)-1)

I have tried this on my system in a printf and it yields a
reasonable value but I do not fully understand how it it
evaluated. size_t is a /type/, defined on my system as

typedef unsigned int size_t;

The part I do not understand is the the meaning of subtracting 1
from a /type/ rather than an expression? How does the compiler
evaluate this?

Oz
 
I

Ian Collins

ozbear said:
In another thread related to size_t and SIZE_MAX, a #define
was suggested for SIZE_MAX where is it not predefined.

The #define was:

#define MY_SIZE_MAX ((size_t)-1)

I have tried this on my system in a printf and it yields a
reasonable value but I do not fully understand how it it
evaluated. size_t is a /type/, defined on my system as

typedef unsigned int size_t;

The part I do not understand is the the meaning of subtracting 1
from a /type/ rather than an expression? How does the compiler
evaluate this?
It's not a subtraction, it's a cast!
 
K

Keith Thompson

In another thread related to size_t and SIZE_MAX, a #define
was suggested for SIZE_MAX where is it not predefined.

The #define was:

#define MY_SIZE_MAX ((size_t)-1)

I have tried this on my system in a printf and it yields a
reasonable value but I do not fully understand how it it
evaluated. size_t is a /type/, defined on my system as

typedef unsigned int size_t;

The part I do not understand is the the meaning of subtracting 1
from a /type/ rather than an expression? How does the compiler
evaluate this?

As Ian Collins already posted, it's a cast, not a subtraction.

Looking at the expression in painful detail from the inside out:

``1'' is an integer constant.

``-1'' is an expression consisting of a unary "-" applied to ``1''.
It's value is -1, and its type is int.

``(size_t)-1'' is a cast expression, specifying that the result of the
expression ``-1'' is to be converted to type size_t. Given the the
rules for converting a signed int value to an unsigned type, the
result is the maximum value of type size_t.

Finally, we put parentheses around the whole thing because it's a
macro definition.
 
O

ozbear

D'OH!
Now I feel like an idiot. Of course it's a cast....
A perfect example of not being able to see what something
really is after you've made up your mind what it is.

Many thanks to all that replied.

Oz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top