Three programs with sizeof

A

Alex Vinokur

Here are three programs.

--- foo1.cpp ---
int foo;
int main()
{
struct foo {};
sizeof (foo);
return 0;
}
----------------

--- foo2.cpp ---
int foo;
int main()
{
struct foo {};
sizeof foo; // Line#5
return 0;
}
----------------

--- foo3.cpp ---
int foo;
int main()
{
sizeof foo;
return 0;
}
----------------


=== Compilation ===

$ g++ --version
g++ (GCC) 3.3.1 (cygming special)
[---omitted---]


$ g++ foo1.cpp
// No errors, no warnings


$ g++ foo2.cpp
foo2.cpp: In function `int main()':
foo2.cpp:5: error: syntax error before `;' token


$ g++ foo3.cpp
// No errors, no warnings

===================


Is g++ right while compiling foo2.cpp?
Why doesn't the compiler see 'int foo'?
 
F

Fraser Ross

"Alex Vinokur"
Is g++ right while compiling foo2.cpp?
Why doesn't the compiler see 'int foo'?

It is correct with the error since the syntax for using sizeof with a
type-name is to have brackets around the type-name. Name lookup rules is
the answer to the second question. If this is wrong then do correct me.

Fraser.
 
R

Ron Natalie

Fraser Ross said:
"Alex Vinokur"

It is correct with the error since the syntax for using sizeof with a
type-name is to have brackets around the type-name. Name lookup rules is
the answer to the second question. If this is wrong then do correct me.
You're quite right. Syntactically in the problem case foo is a typename.
"sizeof foo" is therefore ill-formed. Typename arguments sizeof need
parentheses around them.
 

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

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top