structure vs variable

C

cob

Are there any situations where it might be better to use

struct a { int i };

rather than

int i; ?

Why would one ever do this?
 
J

John Harrison

cob said:
Are there any situations where it might be better to use

struct a { int i };

rather than

int i; ?

Why would one ever do this?

Homework? Good question anyway.

You might to the above if you wanted a type which was 'int-like' but
distinguishable from a normal int in function overloading (for instance).
You might do it is you wanted an 'int-like' type but wanted to suppress some
of the normal behaviour of an int (automatic conversion to double for
instance).

I'm sure you can think of some more cases.

john
 
T

Thomas Matthews

cob said:
Are there any situations where it might be better to use

struct a { int i };

rather than

int i; ?

Why would one ever do this?

One reason is as a foundation to test algorithms.
If the algorithm works with a single int in the structure,
then adding another member won't add much to the design
or program structure.

Another reason may be variable alignment. Some implementations
align structures on a given boundaries but not individual
variables.


--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 
J

jeffc

cob said:
Are there any situations where it might be better to use

struct a { int i };

rather than

int i; ?

Why would one ever do this?

Obviously you can write a constructor for a struct. Not that it would do
you much good, but at least you could initialize it to 0 automatically.
 
E

E. Robert Tisdale

cob said:
Are there any situations where it might be better to use

struct a { int i };

rather than

int i; // ?

Why would one ever do this?

Abstraction.

struct Integer {
private:
// representation
int I;
public:
// functions, operators and constructors
};

Using Integer instead of int permits you
to redefine functions and operations on type int
or even to change the representation of Integer
without consideration for the impact those changes
will have on programs that use type Integer.
 

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

Staff online

Members online

Forum statistics

Threads
474,162
Messages
2,570,893
Members
47,432
Latest member
GTRNorbert

Latest Threads

Top