Article View: comp.lang.c.moderated
Article #2541Re: void* type
From: Ola Liljedahl
Date: Mon, 08 Apr 1996 16:07
Date: Mon, 08 Apr 1996 16:07
54 lines
1957 bytes
1957 bytes
Ok, time for my submission to this old thread.
My approach to a (generic) swap routine is that is must be reentrant
(no static buffers here!) and also should not dynamically allocate memory.
So we swap in place. Byte for byte (or char for char). It compiles cleanly
with gcc-2.7.2 (but gcc is not THE benchmark for STDC-compliant programs,
I know that).
---Programs follows---
#include <assert.h>
#include <stdio.h>
#include <stddef.h>
#define SWAP(a, b) memswap(&(a), &(b), sizeof(a))
static void
memswap(void *_a, void *_b, register size_t size)
{
if (_a != _b)
{
register char *a = _a;
register char *b = _b;
/* Assert that objects don't overlap. */
assert(a + size <= b || b + size <= a);
for (; size != 0; size--, a++, b++)
{
register int c = *a;
*a = *b;
*b = c;
/* This loop could be optimized, for instance by checking
for suitable alignment of a and b pointers and copying
larger units instead of bytes. */
}
}
}
int main()
{
double x = 1.0, y = 2.0;
printf("before swap: x = %f, y = %f\n", x, y);
SWAP(x, y);
printf("after swap: x = %f, y = %f\n", x, y);
return 0;
}
---Program ends---
Mufsi:tmp> gcc -g -Wall -ansi -pedantic swap.c -o swap
Mufsi:tmp> swap
before swap: x = 1.000000, y = 2.000000
after swap: x = 2.000000, y = 1.000000
Mufsi:tmp>
Ola Liljedahl
olli@enea.se
"OSE - Design on a higher level"
Technical Details
Message-ID:
<4kbdkt$e8k@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4iepre$ag7@solutions.solon.com> <4ja3qf$p9b@solutions.solon.com> <4jq1e4$a2g@solutions.solon.com> <4jtud1$3ug@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: olli@enea.se (Ola Liljedahl) Newsgroups: comp.lang.c.moderated Subject: Re: void* type Date: 8 Apr 1996 11:07:57 -0500 Organization: Enea OSE Systems AB; "OSE - Design on a higher level" Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4kbdkt$e8k@solutions.solon.com> References: <4iepre$ag7@solutions.solon.com> <4ja3qf$p9b@solutions.solon.com> <4jq1e4$a2g@solutions.solon.com> <4jtud1$3ug@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com