comp.lang.c
[Top] [All Lists]

Re: sizeof(x)

Subject: Re: sizeofx
From: Keith Thompson
Date: Sun, 30 Mar 2008 14:30:47 -0700
Newsgroups: comp.lang.c

Ioannis Vranos <ivranos@xxxxxxxxxxxxxxxxxxxxxxxxx> writes:
> Ian Collins wrote:
>> Ioannis Vranos wrote:
>>> Ioannis Vranos wrote:
>>>> I first saw that only sizeof x is valid at the pdf hosted at
>>>> http://cprog.tomsweb.net.
>>>
>>> More specifically the above writes:
>>>
>>> "sizeof      Returns size of operand in bytes; two forms:
>>>                               1) sizeof(type)
>>>                               2) sizeof expression"
>>>
>>>
>> Did you read what Harald said: "(x) is a perfectly valid expression"?
>
> ... right. However sizeofx doesn't compile and if (x) was considered an
> expression it should be sizeof (x), and sizeof(x) shouldn't compile.

C code is split into tokens before those tokens are parsed.  (The
process actually involves "preprocessor tokens", which are later
converted to "tokens", but that doesn't matter in this case.)

``sizeof'' is a keyword; like all keywords, it has the form of an
identifier.  ``('' and ``)'' are punctuators.  Two adjacent
identifiers, keywords, or numeric constants must be separated by
whitespace (a comment counts as whitespace).  A keyword and a
punctuator don't need any whitespace to separate them.

``sizeofx'' is just a single identifier that has nothing to do with
the ``sizeof'' keyword.  It compiles just fine if you happen to have
declared it:

    int sizeofx = 42;
    sizeofx;

``sizeof x'' is two tokens, ``sizeof'' and ``x''.  If ``x'' is an
expression (actually a unary-expression; see the grammar), then that's
a legal expression.

``sizeof(x)'' is four tokens, ``sizeof'', ``('', ``x'', and ``)''.  If
``x'' is a type-name, then that's a valid expression.  If ``x'' is an
expression, then ``(x)'' is also a valid expression, and the whole
thing is also a valid expression.

-- 
Keith Thompson (The_Other_Keith) <kst-u@xxxxxxx>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy