473,746 Members | 2,268 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Typedef question

mdh
A quick ? :-) question about Typedefs.
There is a very brief discussion about this in K&R ( p146). Googling
this group, there is a surprising dearth of questions about these.
From one of the threads, there is sound advice ( to me at any rate)
not to hide pointers behind typedefs.
So, may I ask the group when the use of typedefs really makes sense?

Sorry if this is somewhat general, but there are no exercises ( not
that I am asking for any!!) provided.
Sep 2 '08 #1
16 2776
mdh wrote:
A quick ? :-) question about Typedefs.
There is a very brief discussion about this in K&R ( p146). Googling
this group, there is a surprising dearth of questions about these.
From one of the threads, there is sound advice ( to me at any rate)
not to hide pointers behind typedefs.
So, may I ask the group when the use of typedefs really makes sense?
One important use for typedef is to deal with the variability
of C's native types from machine to machine. For example, Park and
Miller's "Minimal Standard Random Number Generator" uses numbers as
large as 2147483646. Many machines' int type will suffice for this
magnitude, but on some you may need to resort to long. You could
just use long everywhere in the code, but on some machines that may
be overkill. Here's a possible solution:

#include <limits.h>
#if INT_MAX >= 2147483646
typedef int MSint; /* int is enough */
#else
typedef long MSint; /* int too small; use long */
#endif

.... and then write the code using MSint throughout. The typedef
encapsulates your choice of the appropriate native type to use in
the environment at hand. It doesn't solve every problem -- for
example, if you use printf() or scanf() with these numbers, you
need to choose the right format strings -- but it can smooth out
a good many machine-to-machine differences.

Another important use is to improve readability by decomposing
complicated declarations into manageable pieces. The classic example
of this is the declaration of the signal() function:

void (*signal(int sig, void (*func)(int)))( int);

Most people will find the code more readable if a typedef is used
(there's more than one way to do this):

typedef void (SigHandler)(in t sig);
SigHandler *signal(int sig, SigHandler *func);

Another use is to attach suggestive one-word names to struct
and union types, as in

typedef struct hashItem {
unsigned int hashValue;
const void *itemPointer;
struct hashItem *nextItem;
} HashItem;

People differ about whether this is a good idea or not. Some feel
that the struct-ness of the thing cannot be hidden (you're going to
use . and -with it, after all), so the attempt to hide it is
feeble and maybe even obfuscatory. Others feel that it's quicker and
easier to write and read `HashItem' than `struct hashItem', and that
using the shorter phrase improves readability. I'm in the latter camp
(especially when the nature of the struct or union is private to a
library and only a `HashItem*' is exported to the clients), but my
preference isn't so strong that I'd take up arms against the
unbelievers. You'll have to consult your own tastes on this one.

Finally, the pointer thing. Even when a library traffics in
pointers to private structs, the fact that they're pointers is usually
something the caller must know, if for no other reason than to test
a returned value against NULL. For this reason, I'd prefer to say
that a function returns a `HashItem*' than a `HashItemPointe r'; the
latter just makes it harder to discern what you're dealing with.
(Is this stance inconsistent with my preference for `HashItem' over
`struct hashItem'? Probably, but as I said earlier I'm not going to
war over it.)

--
Er*********@sun .com
Sep 2 '08 #2
mdh wrote:
A quick ? :-) question about Typedefs.
There is a very brief discussion about this in K&R ( p146). Googling
this group, there is a surprising dearth of questions about these.
From one of the threads, there is sound advice ( to me at any rate)
not to hide pointers behind typedefs.
So, may I ask the group when the use of typedefs really makes sense?

Sorry if this is somewhat general, but there are no exercises ( not
that I am asking for any!!) provided.
Typedefs serve at least two main purposes. The most common one is to
allow you to write code that uses a particular type, when you
anticipate that the type it should use might be different in different
contexts. A simple example is size_t, which is a typedef set up by the
C standard library itself. It might be 'unsigned char' on one
implementation, and "unsigned long long" on another. However, you
don't have to make any changes to your code when moving it from one
implementation to the other, because the change occurs inside the C
standard headers that typedef size_t..

The second use I've seen is for simplifying type declarations. If you
make a lot of use of unsigned char, it's convenient to use

typedef unsigned char uchar;

Similarly, it's convenient to use

typedef struct { int i; double d; } intdouble;

rather than

struct intdouble { int i; double d;};

mainly because it allows you to refer to the type using "intdouble"
rather than "struct intdouble". This is especially attractive to
people who are used to C++, where the keyword struct would be needed
only in the definition of the type, and not when using it.

And, as you've already seen, typedef can be used to simplify code that
relies upon function pointers.
Sep 2 '08 #3
mdh
On Sep 2, 12:47*pm, Eric Sosman <Eric.Sos...@su n.comwrote:
mdh wrote:
A quick ? :-) question about Typedefs.
* * *One important use for typedef is to deal with the variability
of C's native types from machine to machine.
* * *Another important use is to improve readability by decomposing
complicated declarations into manageable pieces.

Eric.Sos...@sun .com
thank you Eric for that explanation.
Sep 2 '08 #4
mdh
On Sep 2, 12:50*pm, jameskuy...@ver izon.net wrote:
mdh wrote:
A quick ? :-) question about Typedefs.
>
Typedefs serve at least two main purposes. The most common one is to
allow you to write code that uses a particular type.
The second use I've seen is for simplifying type declarations. If you
make a lot of use of unsigned char, it's convenient to use

thank you James. Appreciated.
Sep 2 '08 #5
On Sep 2, 10:50 pm, jameskuy...@ver izon.net wrote:
mdh wrote:
A quick ? :-) question about Typedefs.
There is a very brief discussion about this in K&R ( p146). Googling
this group, there is a surprising dearth of questions about these.
From one of the threads, there is sound advice ( to me at any rate)
not to hide pointers behind typedefs.
So, may I ask the group when the use of typedefs really makes sense?
Sorry if this is somewhat general, but there are no exercises ( not
that I am asking for any!!) provided.

Typedefs serve at least two main purposes. The most common one is to
allow you to write code that uses a particular type, when you
anticipate that the type it should use might be different in different
contexts. A simple example is size_t, which is a typedef set up by the
C standard library itself. It might be 'unsigned char' on one
implementation, and "unsigned long long" on another. However, you
don't have to make any changes to your code when moving it from one
implementation to the other, because the change occurs inside the C
standard headers that typedef size_t..

The second use I've seen is for simplifying type declarations. If you
make a lot of use of unsigned char, it's convenient to use

typedef unsigned char uchar;
Ugh. I don't really like code that does that. Also code that has u8,
uchar8 etc.
IMHO typedef is not there to save you typing. You could edit your
editor so whenever you type `uchar ' it replaces it with unsigned
char.
Sep 2 '08 #6
In article <1220384800.358 284@news1nwk>,
Eric Sosman <Er*********@su n.comwrote:
Finally, the pointer thing. Even when a library traffics in
pointers to private structs, the fact that they're pointers is usually
something the caller must know, if for no other reason than to test
a returned value against NULL. For this reason, I'd prefer to say
that a function returns a `HashItem*' than a `HashItemPointe r'; the
latter just makes it harder to discern what you're dealing with.
(Is this stance inconsistent with my preference for `HashItem' over
`struct hashItem'? Probably, but as I said earlier I'm not going to
war over it.)
I disagree that this is inconsistent; since pointerness is important
for the user-programmer to know about, revealing it in the interface
instead of hiding it behind a typedef is an easy way to save the
user-programmer the trouble of making a trip to the documentation to
discover it. Revealing structness in the same way doesn't give
information that's useful (at least, it doesn't if your type is
actually abstract; if you want to give direct information to (some of)
the struct members, then the user-programmer also needs to know that
it's a struct, and in that case hiding structness behind a typedef is
also a Bad Idea).
I dislike hiding both properties behind typedefs; but my dislike for
hiding structness is a purely aesthetic dislike, and my dislike for
hiding pointerness is based on strong opinions about The Way Things
Should Be and on experience with how useful it is to have the
information in front of me while I'm editing code.
dave

--
Dave Vandervies dj3vande at eskimo dot com
I am Aquarion, I am everywhere. There are only 120 real people on the
Internet, and I'm three of them.
--Aquarion in the scary devil monastery
Sep 2 '08 #7
mdh <md**@comcast.n etwrites:
A quick ? :-) question about Typedefs.
There is a very brief discussion about this in K&R ( p146). Googling
this group, there is a surprising dearth of questions about these.
From one of the threads, there is sound advice ( to me at any rate)
not to hide pointers behind typedefs.
So, may I ask the group when the use of typedefs really makes sense?

Sorry if this is somewhat general, but there are no exercises ( not
that I am asking for any!!) provided.
A typedef creates an alias (a name consisting of a single identifer)
for an existing type.

Strictly speaking, typedefs are almost never necessary. (The one
exception, I think, involves the va_arg macro for variadic functions,
which requires a type name that can be used in a certain way.)

It's very common to create a typedef for a struct type. In my opinion
(which plenty of smart programmers don't share), this is poor style.
For example, given:

struct foo {
/* member declarations */
};

the type already has a perfectly good name, "struct foo". Why create
another one? The counterargument is that it's more convenient to have
a simple single-identifier name for the type.

The syntax for function types and pointer-to-function types is
sufficiently convoluted that it can be worthwhile to simplify it by
using typedefs. For example if you want a pointer to a function that
takes a double argument and returns a double result, you can write:

double (*ptr)(double);

or you can write:

typedef double math_func(doubl e);
math_func *ptr;

Or, if you prefer, you can write:

typedef double (*math_func_ptr )(double);

Hiding pointerness behind a typedef is usually a bad idea, but in the
case of a pointer-to-function type it's more defensible.

A typedef is also appropriate when you want an abstract data type,
where code that uses the type shouldn't know anything about its
internals. The type FILE, declared in <stdio.his a good example.
(The use of all-caps isn't particularly consistent with modern style,
which uses all-caps for macros, but it's been around for a very long
time.)

And typedefs are often appropriate for numeric types. I *don't* mean
something like

typedef unsigned int uint;

which does nothing but save you a little typing. I'm referring to a
weaker form of data abstraction, where code that uses the typedef
knows that it's an integer type, and whether it's signed or unsigned,
but doesn't need to know *which* predefined type because it can vary
from one system to another.

To summarize:

Use a typedef when the internal characteristics of the type are
irrelevant to code that uses it (e.g., FILE).

Use a typedef when a named type can be implemented differently on
different systems (e.g., int32_t, size_t).

Use a typedef to give a name to something that can otherwise only be
referred to by some complicated syntax, particularly in the case of
function types and pointer-to-function types.

If you're using a typedef just to save a few keystrokes, don't bother.
Given "typedef unsigned int uint;", uint can never be anything other
than unsigned int; just use its real name, "unsigned int". And if
uint *can* be something other than unsigned int, "uint" is a lousy
name.

Don't bother with typedefs for struct types unless you're doing the
kind of data abstraction I discussed above -- but reasonable people
differ on this.

And I can think of at least one exception to the above. I don't mind

typedef unsigned char byte;

"byte" can never be anything other than unsigned char, but assigning
the name "byte" can make the usage clearer (i.e., this is raw data,
not necessarily characters).

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 3 '08 #8
ja*********@ver izon.net writes:
[...]
The second use I've seen is for simplifying type declarations. If you
make a lot of use of unsigned char, it's convenient to use

typedef unsigned char uchar;
[...]

IMNSHO it's not convenient enough to justify using a typedef rather
than just typing "unsigned char". For one thing, if I'm reading code
that uses "uchar" I'll always have a nagging suspicion that somebody
has decided it would be a cute idea to define it as something other
than unsigned char (say, unsigned short or wchar_t).

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 3 '08 #9
mdh wrote:
So, may I ask the group when the use of typedefs really makes sense?
Yes, you may. ;-)

In addition to the uses already described, I use typedefs for
documentation. For example, I may define a specific type, used in several
places, that is implemented as an unsigned int, but carries specific
attributes. For example,

typedef unsigned int tTimeout; /* timeout interval in ms, 0=none */

When I declare a variable of type tTimeout, I don't need to repeat the
measurement units and special meaning of 0, since it is inherited from the
typedef.

--
Thad
Sep 3 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2959
by: Generic Usenet Account | last post by:
This is a two-part question. (1) I have implemented a "Datastructure Registry" template class. I am getting no compiler warnings with older compilers, but newer compilers are generating the following error messages: warning: implicit typename is deprecated, please see the documentation for details Can someone kindly suggest how to get rid of these warnings? The source code follows.
7
2147
by: Tony Johansson | last post by:
Hello Experts! I have the following Array template class see below. I execute these three statements statement 1: Array<int> x(5); statement 2: cin >>x; statement 3: Array<int>::element_type y = x; but I can't understand the last one which is Array<int>::element_type y = x; We have a typedef T element_type; in the template Array class see below
30
4261
by: stephen henry | last post by:
Hi all, I have a question that I'm having difficulty answering. If I have a struct: typedef struct my_struct_tag{ struct my_other_struct *other; } my_struct_tag
6
7339
by: Alex | last post by:
Hello people, I am getting errors from VS2003 when working with typedef'ed types. For example, assume that I have a type T, defined in a 3rd party include file based on some condition #if (condition) typedef char T; #else typedef short T;
12
8240
by: Thomas Carter | last post by:
Imagine that there is some include file f.h that contains the following line: typedef unsigned int ui32 ; My question is: If I have a C source file F.c that includes f.h, is it possible for the preprocessor to detect that ui32 already exists, when preprocessing F.c? The idea is that F.c will typedef ui32 as above if and only if such typedef is not already in some include file used by F.c.
7
15288
by: Michael B Allen | last post by:
I have a forward reference like: struct foo; int some_fn(struct foo *param); Because the parameter is a pointer the compiler is satisfied. But now I wan to change 'struct foo' to a typedef'd type like 'foo_t'. The following all fail to compile:
4
1716
by: Fei Liu | last post by:
Hello, this is a follow-up question I had about typedef usage in Gianni Mariani's thread: news://213.88.137.53:119/46198ecf$0$13145$5a62ac22@per-qv1-newsreader-01.iinet.net.au int foo(int A, int * pA){ return 0; } int main(){ typedef int * pi; typedef int ii; int a = sizeof(foo(ii(), pi())); }
12
4650
by: Googy | last post by:
Hi!! Can any one explain me the meaning of following notations clearly : 1. typedef char(*(*frpapfrc()))(); frpapfrc f; 2. typedef int (*(arr2d_ptr)()); arr2d_ptr p; 3. typedef int (*(*(*ptr2d_fptr)()))();
7
18447
by: MJ_India | last post by:
Style 1: struct my_struct { ... }; typedef my_struct my_struct_t; Style 2: typedef struct my_struct {
0
8975
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9351
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9286
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8229
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6774
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6062
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4587
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3294
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2200
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.