468,771 Members | 1,551 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,771 developers. It's quick & easy.

sizeof() style question

Some people say sizeof(type) and other say sizeof(variable).
Why?
Nov 14 '05 #1
42 2086
Christopher C. Stacy wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


You mean: One can apply the sizeof operator either to a
cast expression, i.e. (type), or to an expression, e.g
variable or *variable. Both are valid uses, in both cases
you get the size (in bytes) of the type of the expression.

The latter is especially convenient in conjunction with
malloc():

type *p;
p = malloc(some_number * sizeof *p);

works for arbitrary type "type", whereas sizeof (type) works
only as long guaranteed as p is a pointer to type.

Using parentheses around *p is a sign of confusion. If you
want parentheses, use: (sizeof *p).
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
On Thu, 09 Jun 2005 22:15:38 GMT, cs****@news.dtpq.com (Christopher C.
Stacy) wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


Some people are right, and some people are wrong, I guess? ;-)

The syntax for unary operators is pretty clear -

sizeof unary-expression
sizeof(type-name)

Of course, putting an expression in parenthesis has no effect so both
forms are ok. Although I do not use parentheses for both forms, I
suspect that using parentheses probably cuts down on potential errors
of the type sizeof type.
--

Best wishes,

Bob
Nov 14 '05 #3
Christopher C. Stacy wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


The sizeof operator has two forms. From the standard:

The sizeof operator yields the size (in bytes) of its
operand, which may be an expression or the parenthesized
name of a type. The size is determined from the type of the
operand. The result is an integer. If the type of the
operand is a variable length array type, the operand is
evaluated; otherwise, the operand is not evaluated and the
result is an integer constant.

So either
sizeof(type)
or
sizeof expression
is correct, depending on the situation.
Some people, for reasons known only to them, insist on parenthesizing
the expression, but
sizeof(expression)
and
sizeof expression
mean exactly the same thing. Note that 'sizeof variable' is only a
special case of 'sizeof expression'.
In the real world, 'sizeof expression' is much more useful, since it can
be used in situations where the expression is not permanently tied to a
particular type.

Consider a simple situation frequently asked about here: how do you
determine the number of elements in an array declared as an array in the
present scope? The macro
#define NUMBER_OF_ELEMENTS(x) (sizeof(x)/sizeof *(x))
can take the array name without regard for the type of its elements.
BTW, the parentheses about 'x' in the macro have to do with expansion of
macros, not with the operand of sizeof.
Nov 14 '05 #4
Christopher C. Stacy wrote:

Some people say sizeof(type) and other say sizeof(variable).
Why?


I prefer sizeof variable.
There's usually a variable around somewhere
of the type that you're interested in,
.... otherwise why would you be interested in that type?

--
pete
Nov 14 '05 #5
cs****@news.dtpq.com (Christopher C. Stacy) writes:
Some people say sizeof(type) and other say sizeof(variable).
Why?


Some people what to know the size of a type; others want to know the
size of a variable.

Can you be more specific?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6
Michael Mair <Mi**********@invalid.invalid> writes:
Christopher C. Stacy wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


You mean: One can apply the sizeof operator either to a
cast expression, i.e. (type), or to an expression, e.g
variable or *variable. Both are valid uses, in both cases
you get the size (in bytes) of the type of the expression.


In sizeof(type), the (type) has nothing to do with cast expressions,
it's just a type name enclosed in parentheses.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #7


what is the difference between the sizeof(char *) and the sizeof(const char
*) ?

and what is the mean of the const qualifier ?

"Michael Mair" <Mi**********@invalid.invalid> wrote in message
news:3g************@individual.net...
Christopher C. Stacy wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


You mean: One can apply the sizeof operator either to a
cast expression, i.e. (type), or to an expression, e.g
variable or *variable. Both are valid uses, in both cases
you get the size (in bytes) of the type of the expression.

The latter is especially convenient in conjunction with
malloc():

type *p;
p = malloc(some_number * sizeof *p);

works for arbitrary type "type", whereas sizeof (type) works
only as long guaranteed as p is a pointer to type.

Using parentheses around *p is a sign of confusion. If you
want parentheses, use: (sizeof *p).
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.

Nov 14 '05 #8
Keith Thompson wrote:
Michael Mair <Mi**********@invalid.invalid> writes:
Christopher C. Stacy wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


You mean: One can apply the sizeof operator either to a
cast expression, i.e. (type), or to an expression, e.g
variable or *variable. Both are valid uses, in both cases
you get the size (in bytes) of the type of the expression.


In sizeof(type), the (type) has nothing to do with cast expressions,
it's just a type name enclosed in parentheses.


You are right; I don't know where I picked up "cast expression".
My apologies for the wrong information.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #9
Keith Thompson <ks***@mib.org> writes:
Michael Mair <Mi**********@invalid.invalid> writes:
Christopher C. Stacy wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


You mean: One can apply the sizeof operator either to a
cast expression, i.e. (type), or to an expression, e.g
variable or *variable. Both are valid uses, in both cases
you get the size (in bytes) of the type of the expression.


In sizeof(type), the (type) has nothing to do with cast expressions,
it's just a type name enclosed in parentheses.


They have nothing to do with each other, except that a type operand of
'sizeof' and a prefix that specifies casting happen to have identical
syntax, namely '( type-name )'. I expect that's more than just a
coincidence.
Nov 14 '05 #10
On Thu, 09 Jun 2005 18:58:39 -0400, Robert W Hand
<rw****@NOSPAMoperamail.com> wrote:
On Thu, 09 Jun 2005 22:15:38 GMT, cs****@news.dtpq.com (Christopher C.
Stacy) wrote:
Some people say sizeof(type) and other say sizeof(variable).
Why?


Some people are right, and some people are wrong, I guess? ;-)

The syntax for unary operators is pretty clear -

sizeof unary-expression
sizeof(type-name)

Of course, putting an expression in parenthesis has no effect so both
forms are ok. Although I do not use parentheses for both forms, I
suspect that using parentheses probably cuts down on potential errors
of the type sizeof type.


I find that having a unary operator which is an identifier is a
cognitive dissonance in C (I don't use the word forms of &&, ||, ! etc.
either). And if one of them needs a parenthesis, both should. Why
(sizeof x) but not (sizeof x_t)? Putting it with parentheses at least
preserves syntax with the rest of the language (it looks like a
parameterised macro or a function call).

Chris C
Nov 14 '05 #11
Tim Rentsch <tx*@alumnus.caltech.edu> writes:
Keith Thompson <ks***@mib.org> writes:

[...]
In sizeof(type), the (type) has nothing to do with cast expressions,
it's just a type name enclosed in parentheses.


They have nothing to do with each other, except that a type operand of
'sizeof' and a prefix that specifies casting happen to have identical
syntax, namely '( type-name )'. I expect that's more than just a
coincidence.


I expect it's just a coincidence. Parentheses are used for enough
different things that it's not surprising a couple of them look alike
when taken out of context.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #12
On Fri, 10 Jun 2005 08:18:34 +0100, Chris Croughton
<ch***@keristor.net> wrote:
The syntax for unary operators is pretty clear -

sizeof unary-expression
sizeof(type-name)

Of course, putting an expression in parenthesis has no effect so both
forms are ok. Although I do not use parentheses for both forms, I
suspect that using parentheses probably cuts down on potential errors
of the type sizeof type.


I find that having a unary operator which is an identifier is a
cognitive dissonance in C (I don't use the word forms of &&, ||, ! etc.
either). And if one of them needs a parenthesis, both should. Why
(sizeof x) but not (sizeof x_t)? Putting it with parentheses at least
preserves syntax with the rest of the language (it looks like a
parameterised macro or a function call).


Never thought that a computer language had a psychological state. ;-)

I guess I have become more flexible in old age. Of course, sizeof
expression is not a macro or function call. Why make it look like
one? Making it look like a function call or macro might lead a newbie
to ask what header to include for sizeof(). It is an operator. Let's
remember to call it an operator.

I have heard the argument from reasonable and experienced programmers
that using parentheses on expressions would cut down on newbie errors
when sizeof(int) is wanted (less likely to write sizeof int). I
understand the argument, but I do not use it.
--

Best wishes,

Bob
Nov 14 '05 #13
In article <j2*****************@newsread3.news.atl.earthlink. net> Martin Ambuhl <ma*****@earthlink.net> writes:
....
The sizeof operator has two forms. From the standard:

The sizeof operator yields the size (in bytes) of its
operand, which may be an expression or the parenthesized
name of a type. The size is determined from the type of the
operand. The result is an integer. If the type of the
operand is a variable length array type, the operand is
evaluated; otherwise, the operand is not evaluated and the
result is an integer constant. .... Some people, for reasons known only to them, insist on parenthesizing
the expression, but
sizeof(expression)
and
sizeof expression
mean exactly the same thing.


Except when expression is a cast expression.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #14
Michael Mair <Mi**********@invalid.invalid> wrote:
Using parentheses around *p is a sign of confusion.


Or perhaps unfortunate style standards...

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #15
Christopher C. Stacy wrote on 10/06/05 :
Some people say sizeof(type) and other say sizeof(variable).
Why?


It depends on the situaton. If you have an object or a typed pointer,
better to use sizeof object or sizeof *p_object (no parens needed). But
if you only have the type, use sizeof (type) (parens required).

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++

Nov 14 '05 #16
On Fri, 10 Jun 2005 12:36:10 +0000, Dik T. Winter wrote:
In article <j2*****************@newsread3.news.atl.earthlink. net> Martin Ambuhl <ma*****@earthlink.net> writes:
...
> The sizeof operator has two forms. From the standard:
>
> The sizeof operator yields the size (in bytes) of its
> operand, which may be an expression or the parenthesized
> name of a type. The size is determined from the type of the
> operand. The result is an integer. If the type of the
> operand is a variable length array type, the operand is
> evaluated; otherwise, the operand is not evaluated and the
> result is an integer constant. ...
> Some people, for reasons known only to them, insist on parenthesizing
> the expression, but
> sizeof(expression)
> and
> sizeof expression
> mean exactly the same thing.


However things like sizeof array + 1 can look awkward. sizeof(array) + 1
looks neater and perhaos clearer. You can write (sizeof array) + 1 but
that still isn't quite as natural
Except when expression is a cast expression.


Well expression has to be syntactically valid as an operand to sizeof. 1+1
isn't e.g. sizeof 1+1 isn't the same thing as sizeof(1+1). A cast
expression isn't a syntactically valid operand of sizeof.

Lawrence

Nov 14 '05 #17

"Chris Croughton" <ch***@keristor.net> wrote
I find that having a unary operator which is an identifier is a
cognitive dissonance in C (I don't use the word forms of &&, ||, ! etc.
either). And if one of them needs a parenthesis, both should. Why
(sizeof x) but not (sizeof x_t)? Putting it with parentheses at least
preserves syntax with the rest of the language (it looks like a
parameterised macro or a function call).

I agree. sizeof is a function, so it sould take its argument in parentheses
like other C functions.
It is a function of the type rather than the value of its argument, so
sizeof(int) is preferable to sizeof(x).
Personally I'm sceptical of the argument that sizeof *ptr is robust to
changes in the type of ptr - anyone who changes the type of a pointer should
scan through all code that references it as a matter of course. However it
is a legitimate point..
Nov 14 '05 #18
"Malcolm" <re*******@btinternet.com> writes:
"Chris Croughton" <ch***@keristor.net> wrote
I find that having a unary operator which is an identifier is a
cognitive dissonance in C (I don't use the word forms of &&, ||, ! etc.
either). And if one of them needs a parenthesis, both should. Why
(sizeof x) but not (sizeof x_t)? Putting it with parentheses at least
preserves syntax with the rest of the language (it looks like a
parameterised macro or a function call).

I agree. sizeof is a function, so it sould take its argument in parentheses
like other C functions.


Would you also argue that return is a function call, so its argument
should be in parentheses? (If so, you're being consistent, but I
disagree; it would also imply that a return with no expression should
be written as "return();", but the language doesn't allow that.)

sizeof is an operator, not a function. It happens to be the only (?)
operator in C whose name is a keyword rather than a symbol composed of
punctuation characters, but there's no fundamental reason operators in
general can't use either form. I've used other languages where some
operators are puncuation symbols, and others are keywords; there's no
real distinction between them other than the way their names are
spelled.

"sizeof" and "&" are both operators; when the operand is an
expression, there's no need to use parentheses unless they're
necessary for grouping or clarity. I'm almost sympathetic to using
"sizeof(*x)" because it looks too much like a multiplication without
the parentheses, but I find that proper spacing, as in "sizeof *x", is
sufficient to get the point across.

Pretending that sizeof is a function will eventually lead to
confusion; for example, it can cause you to forget that the operand
isn't evaluated (unless it's a VLA), and it can make it difficult to
read code written by people who don't choose to pretend that it's a
function. Just remember that operator names don't have to be composed
of punctuation marks, and that sizeof(type) is a special case, and
everything becomes clear.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #19
On Fri, 10 Jun 2005 21:30:56 +0000 (UTC), Malcolm
<re*******@btinternet.com> wrote:
"Chris Croughton" <ch***@keristor.net> wrote
I find that having a unary operator which is an identifier is a
cognitive dissonance in C (I don't use the word forms of &&, ||, ! etc.
either). And if one of them needs a parenthesis, both should. Why
(sizeof x) but not (sizeof x_t)? Putting it with parentheses at least
preserves syntax with the rest of the language (it looks like a
parameterised macro or a function call).
I agree. sizeof is a function, so it sould take its argument in parentheses
like other C functions.


Except that it's a compile-time function. But I agree that in a
mathematical sense the result is a function of the (type of the)
parameter. I don't think that it's really an operator, it doesn't
operate on anything.
It is a function of the type rather than the value of its argument, so
sizeof(int) is preferable to sizeof(x).
IMO, yes. It also ensures that it avoids ambiguity:

malloc(sizeof x * y)

is visually ambiguous, since unlike the ordinary operators the
precedence is not obvious (OK, the precedence of bit operators is odd as
well, so I always fully parenthesise those).
Personally I'm sceptical of the argument that sizeof *ptr is robust to
changes in the type of ptr - anyone who changes the type of a pointer should
scan through all code that references it as a matter of course. However it
is a legitimate point..


If one uses sizeof(*p) then it is less to change, thus there is less
chance of errors getting in by accident. Why make changes more
error-prone than they have to be? For instance, take a typical use of
an allocated array:

int func(size_t n, ...)
{
float *arr = malloc(n * sizeof(*arr));
int i;
if (!arr)
return -1;
for (i = 0; i < n; ++i)
arr[i] = 0.0;
/* use array for calculations */
free(arr);
return result;
}

If I decide to do the calculations in double or long double instead, I
only have one place to change, so I won't be in danger of getting te
wrong amount of memory. If the type were specified also in the malloc
then it would be easy to overlook the change.

Chris C
Nov 14 '05 #20
Keith Thompson <ks***@mib.org> writes:
Tim Rentsch <tx*@alumnus.caltech.edu> writes:
Keith Thompson <ks***@mib.org> writes:

[...]
In sizeof(type), the (type) has nothing to do with cast expressions,
it's just a type name enclosed in parentheses.


They have nothing to do with each other, except that a type operand of
'sizeof' and a prefix that specifies casting happen to have identical
syntax, namely '( type-name )'. I expect that's more than just a
coincidence.


I expect it's just a coincidence. Parentheses are used for enough
different things that it's not surprising a couple of them look alike
when taken out of context.


1. Both are elements of expressional forms;

2. Both have ()'s to prevent undesireable interaction with other parts
of the expression;

3. Both are used to express a "type value";

4. They have identical syntax.

What relevant context would you say is missing?

Nov 14 '05 #21
Chris Croughton wrote:
Except that it's a compile-time function.
Has everybody gone insane?
But I agree that in a
mathematical sense the result is a function of the (type of the)
parameter.
Parameters are automatic objects.
The operand of sizeof has no such constraint.
The result of any operation,
is a function of the operand or operands.
I don't think that it's really an operator, it doesn't
operate on anything.


"operand of the sizeof operator" means nothing to you?

--
pete
Nov 14 '05 #22
Malcolm wrote:
I agree. sizeof is a function, so it sould take its argument in parentheses
like other C functions.
Sorry, but sizeof is not a function. It is an operator.
It is a function of the type rather than the value of its argument, so
sizeof(int) is preferable to sizeof(x).


It is not a function at all. It is incorrect to say of that which is
not a function that it is a function of x rather than a function of y.

Nov 14 '05 #23
On Sat, 11 Jun 2005 07:58:57 +0100, Chris Croughton
<ch***@keristor.net> wrote:
I agree. sizeof is a function, so it sould take its argument in parentheses
like other C functions.


Except that it's a compile-time function. But I agree that in a
mathematical sense the result is a function of the (type of the)
parameter. I don't think that it's really an operator, it doesn't
operate on anything.


I'm sure that some of the problem in this thread is due to mixing
technical and colloquial uses of some terms. Let's be clear, the
technical term for sizeof in the C Standard is operator - not macro,
not function or not even compile-time function.

The "mathematical sense" of function and operator are muddy to start
with. Much of Linear Algebra explores the relationship between
operators and functions. I would not confuse the issue further, by
introducing "mathematical sense" to this discussion.

Let's try to stick to the term in the C Standard - operator.
--

Best wishes,

Bob
Nov 14 '05 #24
On Fri, 10 Jun 2005 21:30:56 +0000, Malcolm wrote:

"Chris Croughton" <ch***@keristor.net> wrote
I find that having a unary operator which is an identifier is a
cognitive dissonance in C (I don't use the word forms of &&, ||, ! etc.
either). And if one of them needs a parenthesis, both should. Why
(sizeof x) but not (sizeof x_t)? Putting it with parentheses at least
preserves syntax with the rest of the language (it looks like a
parameterised macro or a function call).
I agree. sizeof is a function, so it sould take its argument in parentheses
like other C functions.


The key thing to realise is that sizeof CANNOT be a function in C because
C functions cannot take types as arguments, or take type information from
an expression argument. C defines sizeof as a keyword and an operator. As
such it is not bound to function-like syntax. Indeed thinking of it as a
function is an error, because it does not work on the value of its operand.
It is a function of the type
rather than the value of its argument, so
sizeof(int) is preferable to sizeof(x).
In a very theoretical sense you have a small point, but for practical
purposes sizeof x is usually more appropriate than sizeof(int), and C is a
practical language. There are good theory based reasons too, such as
avoiding duplicate definitions of the same information which introduces
risk of consistency errors.
Personally I'm sceptical of the
argument that sizeof *ptr is robust to changes in the type of ptr -
anyone who changes the type of a pointer should scan through all code
that references it as a matter of course. However it is a legitimate
point..


It is certainly robust. There is real risk of missing things if you depend
on scanning code to find them. No risk is the code is correct in the first
place. Also consider that it is easy to get the type wrong in a sizeof e.g.
I've seen plenty of instances of code like

int **ptr;

ptr = malloc(N * sizeof(int));

Writing it like

ptr = malloc(N * sizeof *ptr)

provides a single clear form for most of not all such cases, it is even
uniform enough to be wrapped in a macro such as:

#define MALLOC(ptr, N) ((ptr) = malloc((N) * sizeof *(ptr)))

and which makes usage very simple:

if (MALLOC(ptr, NELEMS) == NULL) {
...
}

Lawrence


Nov 14 '05 #25
Chris Croughton wrote:
.... snip ...
IMO, yes. It also ensures that it avoids ambiguity:

malloc(sizeof x * y)

is visually ambiguous, since unlike the ordinary operators the
precedence is not obvious (OK, the precedence of bit operators
is odd as well, so I always fully parenthesise those).


Which is why I always write that as:

malloc(y * sizeof x)

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #26

"Robert W Hand" <rw****@NOSPAMoperamail.com> wrote

I'm sure that some of the problem in this thread is due to mixing
technical and colloquial uses of some terms. Let's be clear, the
technical term for sizeof in the C Standard is operator - not macro,
not function or not even compile-time function.

The "mathematical sense" of function and operator are muddy to start
with. Much of Linear Algebra explores the relationship between
operators and functions. I would not confuse the issue further, by
introducing "mathematical sense" to this discussion.

Let's try to stick to the term in the C Standard - operator.

Virtually every C compiler will incorporate a function (in the C sense,
probably written in C) called something like getsize(), that takes a type as
an argument and returns the number of bytes occupied. It will be a
moderately complicated function because it has to support structures.

Of course this function is evaluated at compile time, so sizeof resolves to
a constant. Most of the other operators cause small numbers of machine
instructions to be executed, unless all their operands happen to be
constants, which programmers want sometimes for clarity eg 2 * PI.

So it's a peculiar operator in three ways; the evaluation is not
mathematically simple, it doesn't cause runtime instructions to be executed,
and the operand is a type not a scalar.

Basically it is a function of a type. We're just teasing by using the word
"function" because the ANSI committee, in its arrogance, has presumed to
define how this word shall be used.
Nov 14 '05 #27
Tim Rentsch <tx*@alumnus.caltech.edu> writes:
Keith Thompson <ks***@mib.org> writes:
Tim Rentsch <tx*@alumnus.caltech.edu> writes:
> Keith Thompson <ks***@mib.org> writes:

[...]
>> In sizeof(type), the (type) has nothing to do with cast expressions,
>> it's just a type name enclosed in parentheses.
>
> They have nothing to do with each other, except that a type operand of
> 'sizeof' and a prefix that specifies casting happen to have identical
> syntax, namely '( type-name )'. I expect that's more than just a
> coincidence.


I expect it's just a coincidence. Parentheses are used for enough
different things that it's not surprising a couple of them look alike
when taken out of context.


1. Both are elements of expressional forms;

2. Both have ()'s to prevent undesireable interaction with other parts
of the expression;

3. Both are used to express a "type value";

4. They have identical syntax.

What relevant context would you say is missing?


I suppose I was thinking of the fact that the parenthesized type name
is followed by an expression in a cast expression, and isn't in
sizeof(type). That, and the fact that sizeof(type) allows any object
type, and a cast only allows certain types (no unions, structs, or
arrays).

I suppose the real question is whether the inventor(s) of the
sizeof(type) form were thinking of casts when they designed the syntax
(I'm not sure whether it originated in C or in one of its
predecessors). I don't know the answer to that.

Note also that there is no single syntactic construct corresponding to
a parenthesized type name. It can only be part of a cast-expression,
or part of a sizeof(type) expression.

Having said all that, I don't think it's a particularly important
question.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #28

"Robert W Hand" <rw****@NOSPAMoperamail.com> wrote in message
news:j5********************************@4ax.com...
On Sat, 11 Jun 2005 07:58:57 +0100, Chris Croughton
<ch***@keristor.net> wrote:
I agree. sizeof is a function, so it sould take its argument in parentheses like other C functions.


Except that it's a compile-time function. But I agree that in a
mathematical sense the result is a function of the (type of the)
parameter. I don't think that it's really an operator, it doesn't
operate on anything.


I'm sure that some of the problem in this thread is due to mixing
technical and colloquial uses of some terms. Let's be clear, the
technical term for sizeof in the C Standard is operator - not macro,
not function or not even compile-time function.

The "mathematical sense" of function and operator are muddy to start
with. Much of Linear Algebra explores the relationship between
operators and functions. I would not confuse the issue further, by
introducing "mathematical sense" to this discussion.

Let's try to stick to the term in the C Standard - operator.
--

Best wishes,

Bob


Some of us have forgotten most of our Linear Algebra :-).
Nov 14 '05 #29
Michael Mair wrote:
type *p;
p = malloc(some_number * sizeof *p);

works for arbitrary type "type", whereas sizeof (type) works
only as long guaranteed as p is a pointer to type.


And your point here is...? sizeof(variable), sizeof(*variable),
sizeof(type) gives the size, no matter what. And (do not take this too
personally), it's better to put in the parenthesis, to diminish confusion.

-atl-
--
A multiverse is figments of its own creations
Nov 14 '05 #30
Ari Lukumies <ar**********@gmail.com> writes:
Michael Mair wrote:
type *p;
p = malloc(some_number * sizeof *p);
works for arbitrary type "type", whereas sizeof (type) works
only as long guaranteed as p is a pointer to type.
And your point here is...? sizeof(variable), sizeof(*variable),
sizeof(type) gives the size, no matter what.


The point is maintainability.

Suppose the initial version of your program has:

int *p;
p = malloc(some_number * sizeof(int));

Later, you change the type of p from int* to long* -- but you forget
to change the malloc call, introducing a bug that takes hours or days
to track down. It could take even longer if int and long happen to be
the same size on your development platform, and the bug has no
symptoms until you port to another system months later.

Using sizeof *p avoids this.
And (do not take this too
personally), it's better to put in the parenthesis, to diminish
confusion.


I'm not entirely unsympathetic to that point, but sizeof is a unary
operator, not a function. Its name just happens to be spelled with
letters rather than punctuation marks. It's no more necessary to
parenthesize the argument in "sizeof var" than in "- var". There are,
of course, cases where parentheses add to clarity, but once you
understand what's going on with sizeof, I don't think this is one of
them.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #31
cs****@news.dtpq.com (Christopher C. Stacy) writes:
Some people say sizeof(type) and other say sizeof(variable).
Why?


I've been reading the thread discussing 'sizeof' and its usage with
interest. I've gone back and forth a bit in my own development
practices for using sizeof, and the discussion has sharpened
my views enough so I'm ready to offer my $0.02 now.

Executive summary - prefer sizeof(x), sizeof(*p) to sizeof(type).

First, the starting question, 'sizeof(type)' or 'sizeof(variable)'?
Looking through several hundred thousand lines of code, I'm convinced
'sizeof(variable)' [or 'sizeof(expression)'] is almost always better
than 'sizeof(type)'. Using 'sizeof(type)' is similar to using "magic
numbers" in open code - better to relegate those few cases that really
need to do 'sizeof(type)' to #defines, and then use the symbolic name.

Second, to parenthesize or not parenthesize? I think the easiest way
to think of 'sizeof' is as a special kind of macro, much like the
special macro 'offsetof()', and just always use parentheses. I know
that technically that isn't right, but it's easy to explain, easy to
remember, and reduces cognitive load when reading code. What about
people who use the 'sizeof x' form, without parentheses? I wouldn't
object to that too strongly, kind of put it in the category of writing
indexing with the integer on the outside, eg, 0[p] -- experts do it,
and if one wants to be considered an expert one should know about it,
but it's not necessary to use it just because you can.

Third, related topic, sharing a little macro definition that I've
found useful:

#define bitsizeof(x) (sizeof(x) * CHAR_BIT)

Of course this needs a #include <limits.h> to work properly.
Nov 14 '05 #32

In article <sl******************@ccserver.keris.net>, Chris Croughton <ch***@keristor.net> writes:
On Fri, 10 Jun 2005 21:30:56 +0000 (UTC), Malcolm
<re*******@btinternet.com> wrote:

Except that it's a compile-time function. But I agree that in a
mathematical sense the result is a function of the (type of the)
parameter. I don't think that it's really an operator, it doesn't
operate on anything.


Nonsense. Mathematical operators *are* functions - there's no
relevant distinction there. sizeof is a unary operator, and it
operates on its argument, mapping from the domain that's the union of
{identifiers naming complete types} and {identifiers naming objects
of complete type}, to the range [0,SIZE_MAX].

It's just as much an operator as, say, unary negation (-) or bitwise
negation (~). It happens to have a different domain and range, but
that doesn't magically change it from an "operator" to a "function" -
that's a meaningless distinction in mathematics, and simply wrong in
C.

An operator or function only "doesn't operate on anything" if its
domain is the empty set. sizeof takes an argument; thus it operates
on something.
It is a function of the type rather than the value of its argument, so
sizeof(int) is preferable to sizeof(x).


IMO, yes. It also ensures that it avoids ambiguity:

malloc(sizeof x * y)

is visually ambiguous, since unlike the ordinary operators the
precedence is not obvious (OK, the precedence of bit operators is odd as
well, so I always fully parenthesise those).


What's "visually ambiguous" depends on the reader. Do you find unary
negation ambiguous in the same context? Your argument applies just
as well to it.

--
Michael Wojcik mi************@microfocus.com

Art is our chief means of breaking bread with the dead ... but the social
and political history of Europe would be exactly the same if Dante and
Shakespeare and Mozart had never lived. -- W. H. Auden
Nov 14 '05 #33
On Mon, 13 Jun 2005 15:12:55 +0000, Michael Wojcik wrote:

....
It's just as much an operator as, say, unary negation (-) or bitwise
negation (~). It happens to have a different domain and range, but
that doesn't magically change it from an "operator" to a "function" -
that's a meaningless distinction in mathematics, and simply wrong in
C.

An operator or function only "doesn't operate on anything" if its
domain is the empty set. sizeof takes an argument; thus it operates
on something.


Functions have arguments, operators have operands. :-)

Lawrence

Nov 14 '05 #34
Lawrence Kirby <lk****@netactive.co.uk> writes:
On Mon, 13 Jun 2005 15:12:55 +0000, Michael Wojcik wrote:

......
An operator or function only "doesn't operate on anything" if its
domain is the empty set. sizeof takes an argument; thus it operates
on something.


Functions have arguments, operators have operands. :-)


Functions have parameters.

Function calls (and sometimes comp.lang.c contributors) have arguments.
Nov 14 '05 #35

Le 13/06/2005 23:51, dans kf*************@alumnus.caltech.edu, «*Tim
Rentsch*» <tx*@alumnus.caltech.edu> a écrit*:
Lawrence Kirby <lk****@netactive.co.uk> writes:
On Mon, 13 Jun 2005 15:12:55 +0000, Michael Wojcik wrote:

......
An operator or function only "doesn't operate on anything" if its
domain is the empty set. sizeof takes an argument; thus it operates
on something.


Functions have arguments, operators have operands. :-)


Functions have parameters.

Function calls (and sometimes comp.lang.c contributors) have arguments.


In french we say "chipoteur", I think it's quibbling in english ;-)
This is just an argument argument :-D

Nov 14 '05 #36
Jean-Claude Arbaut <je****************@laposte.net> writes:
Le 13/06/2005 23:51, dans kf*************@alumnus.caltech.edu, «*Tim
Rentsch*» <tx*@alumnus.caltech.edu> a écrit*:
Lawrence Kirby <lk****@netactive.co.uk> writes:
On Mon, 13 Jun 2005 15:12:55 +0000, Michael Wojcik wrote:

......

An operator or function only "doesn't operate on anything" if its
domain is the empty set. sizeof takes an argument; thus it operates
on something.

Functions have arguments, operators have operands. :-)


Functions have parameters.

Function calls (and sometimes comp.lang.c contributors) have arguments.


In french we say "chipoteur", I think it's quibbling in english ;-)
This is just an argument argument :-D


I should have added a smiley. My comments were intended
primarily as humor.
Nov 14 '05 #37
On Mon, 13 Jun 2005 14:51:07 -0700, Tim Rentsch wrote:
Lawrence Kirby <lk****@netactive.co.uk> writes:
On Mon, 13 Jun 2005 15:12:55 +0000, Michael Wojcik wrote:

......
> An operator or function only "doesn't operate on anything" if its
> domain is the empty set. sizeof takes an argument; thus it operates
> on something.


Functions have arguments, operators have operands. :-)


Functions have parameters.

Function calls (and sometimes comp.lang.c contributors) have arguments.


However this was in the context of an operator invocation/function call. :-)

Lawrence

Nov 14 '05 #38
Jean-Claude Arbaut wrote on 13/06/05 :
In french we say "chipoteur", I think it's quibbling in english ;-)


'F'rench ... 'E'nglish ...

'picky' is the word you are looking for.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

..sig under repair

Nov 14 '05 #39

Le 15/06/2005 18:58, dans mn***********************@YOURBRAnoos.fr,
«*Emmanuel Delahaye*» <em***@YOURBRAnoos.fr> a écrit*:
Jean-Claude Arbaut wrote on 13/06/05 :
In french we say "chipoteur", I think it's quibbling in english ;-)


'F'rench ... 'E'nglish ...

'picky' is the word you are looking for.


But the first line is much more expressive :-)

Nov 14 '05 #40
Lawrence Kirby <lk****@netactive.co.uk> writes:
On Mon, 13 Jun 2005 14:51:07 -0700, Tim Rentsch wrote:
Lawrence Kirby <lk****@netactive.co.uk> writes:
On Mon, 13 Jun 2005 15:12:55 +0000, Michael Wojcik wrote:

......

> An operator or function only "doesn't operate on anything" if its
> domain is the empty set. sizeof takes an argument; thus it operates
> on something.

Functions have arguments, operators have operands. :-)


Functions have parameters.

Function calls (and sometimes comp.lang.c contributors) have arguments.


However this was in the context of an operator invocation/function call. :-)


Right. As I said, my comments were intended primarily as humor.
The posting really should have included a smiley - my sense of
humor is a little too dry at times. :-)
Nov 14 '05 #41
On Thu, 09 Jun 2005 23:13:19 GMT, Martin Ambuhl
<ma*****@earthlink.net> wrote:
<snip>
So either
sizeof(type)
or
sizeof expression
is correct, depending on the situation.
Some people, for reasons known only to them, insist on parenthesizing
the expression, but
sizeof(expression)
and
sizeof expression
mean exactly the same thing. Note that 'sizeof variable' is only a
special case of 'sizeof expression'.


As long as expression does not expose any operator(s) with precedence
below unary; if it does/would the parentheses are needed.

The operators that normally affect (produce) a result type we want to
take the size of like *ptr ptr->mem (str).mem ary[sub] are OK, and the
lower-precedence ones are rarely needed. But if we want, e.g. in a
macro, room for "at least 'long' but bigger if needed for the value"
sizeof ( (x) + 0L ) works but sizeof (x) + 0L doesn't.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #42
On 13 Jun 2005 15:12:55 GMT, mw*****@newsguy.com (Michael Wojcik)
wrote:

In article <sl******************@ccserver.keris.net>, Chris Croughton <ch***@keristor.net> writes:
On Fri, 10 Jun 2005 21:30:56 +0000 (UTC), Malcolm
<re*******@btinternet.com> wrote:

Except that it's a compile-time function. But I agree that in a
mathematical sense the result is a function of the (type of the)
parameter. I don't think that it's really an operator, it doesn't
operate on anything.


Nonsense. Mathematical operators *are* functions - there's no
relevant distinction there. sizeof is a unary operator, and it
operates on its argument, mapping from the domain that's the union of
{identifiers naming complete types} and {identifiers naming objects
of complete type}, to the range [0,SIZE_MAX].

Not just identifiers. It accepts the union of parenthesized type-name,
which is approximately an abstract declaration, with unary-expression
which would evaluate if executed (except for VLA) to an lvalue
(object) *or (r)value* of complete type, including as one case a
parenthesized (general-)expression. The things it's *useful* to get
the size of are usually lvalues and objects, and often simply
identified ones, but it's not limited to that.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #43

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

33 posts views Thread by Metzen | last post: by
19 posts views Thread by Martin Pohlack | last post: by
15 posts views Thread by fdunne2 | last post: by
43 posts views Thread by Richard | last post: by
28 posts views Thread by Howard Bryce | last post: by
27 posts views Thread by CodeMonk3y | last post: by
3 posts views Thread by sh.vipin | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.