473,387 Members | 1,516 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

K&R exercise 4-14

The question is "define a macro swap(t,x,y) that interchanges two
arguments of type t".
What does it mean? what are arugments of a type? I can't find an
explanation in the book.
Nov 14 '05 #1
16 3586
Kevin Zhou <zr*****@hotmail.com> writes:
The question is "define a macro swap(t,x,y) that interchanges two
arguments of type t".
What does it mean? what are arugments of a type? I can't find an
explanation in the book.


Types don't have arguments. The macro takes three arguments.
The first (t) is a type, and the second and third (x and y) have
the type specified by the first argument.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #2
Ben Pfaff wrote:
Kevin Zhou <zr*****@hotmail.com> writes:

The question is "define a macro swap(t,x,y) that interchanges two
arguments of type t".
What does it mean? what are arugments of a type? I can't find an
explanation in the book.

Types don't have arguments. The macro takes three arguments.
The first (t) is a type, and the second and third (x and y) have
the type specified by the first argument.

Thanks for the clarification.
Here's a solution I found at
http://users.powernet.co.uk/eton/kandr2/krx414.html

#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)

why a do while "loop" is necessay ?
Nov 14 '05 #3
Kevin Zhou <zr*****@hotmail.com> writes:
#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)

why a do while "loop" is necessay ?


This is in the C FAQ.

10.4: What's the best way to write a multi-statement macro?

A: The usual goal is to write a macro that can be invoked as if it
were a statement consisting of a single function call. This
means that the "caller" will be supplying the final semicolon,
so the macro body should not. The macro body cannot therefore
be a simple brace-enclosed compound statement, because syntax
errors would result if it were invoked (apparently as a single
statement, but with a resultant extra semicolon) as the if
branch of an if/else statement with an explicit else clause.

The traditional solution, therefore, is to use

#define MACRO(arg1, arg2) do { \
/* declarations */ \
stmt1; \
stmt2; \
/* ... */ \
} while(0) /* (no trailing ; ) */

When the caller appends a semicolon, this expansion becomes a
single statement regardless of context. (An optimizing compiler
will remove any "dead" tests or branches on the constant
condition 0, although lint may complain.)

If all of the statements in the intended macro are simple
expressions, with no declarations or loops, another technique is
to write a single, parenthesized expression using one or more
comma operators. (For an example, see the first DEBUG() macro
in question 10.26.) This technique also allows a value to be
"returned."

References: H&S Sec. 3.3.2 p. 45; CT&P Sec. 6.3 pp. 82-3.

--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #4
Kevin Zhou wrote:
Ben Pfaff wrote:
Kevin Zhou <zr*****@hotmail.com> writes:

The question is "define a macro swap(t,x,y) that interchanges
two arguments of type t". What does it mean? what are
arugments of a type? I can't find an explanation in the book.


Types don't have arguments. The macro takes three arguments.
The first (t) is a type, and the second and third (x and y)
have the type specified by the first argument.


Thanks for the clarification.
Here's a solution I found at
http://users.powernet.co.uk/eton/kandr2/krx414.html

#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)

why a do while "loop" is necessay ?


Read the c-faq listed below for the reason.

--
Some useful references:
<http://www.ungerhu.com/jxh/clc.welcome.txt>
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)

Nov 14 '05 #5

"Kevin Zhou" <zr*****@hotmail.com> wrote in message

#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)

why a do while "loop" is necessay ?

This is a really bad exercise. Macros in C are word-processing commands,
which means that you have to do lots of tricks to do anything beyond the
simple
#define constant 123
or an extremely simple function. Even min and max have problems if arguments
have side effects, and need lots of ugly parentheses to cope with compound
arguments.

If we didn't use the do ... while trick we would have a floating {} block,
which is illegal.
Nov 14 '05 #6
In 'comp.lang.c', Kevin Zhou <zr*****@hotmail.com> wrote:
The question is "define a macro swap(t,x,y) that interchanges two
arguments of type t".
What does it mean? what are arugments of a type? I can't find an
explanation in the book.


Bad parsing:

"define a macro swap(t,x,y) that interchanges two arguments <breath> of type
t"

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #7
In 'comp.lang.c', "Malcolm" <ma*****@55bank.freeserve.co.uk> wrote:
#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)
If we didn't use the do ... while trick we would have a floating {}
block, which is illegal.


Wow! Since when has a 'floating block' been illegal? I'm curious. I use it
daily to stick to my 'reduce the range of the objects' policy...

No, the reason for the do-while trick in macros is to force the use of the
final ';' in the source code. Isn't it explained like that in the FAQ?

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #8
On Sat, 08 May 2004 23:19:51 -0400, Kevin Zhou <zr*****@hotmail.com>
wrote:
http://users.powernet.co.uk/eton/kandr2/krx414.html

#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)


I hope that before you submit your coursework you can
find and fix the deliberate typo. :)

Nick.

Nov 14 '05 #9
Nick Austin wrote:
On Sat, 08 May 2004 23:19:51 -0400, Kevin Zhou <zr*****@hotmail.com>
wrote:

http://users.powernet.co.uk/eton/kandr2/krx414.html

#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)

I hope that before you submit your coursework you can
find and fix the deliberate typo. :)

Nick.

Actually I'm learning C from the book for fun.
Nov 14 '05 #10
On Sun, 09 May 2004 16:23:35 -0400, Kevin Zhou <zr*****@hotmail.com>
wrote:
Nick Austin wrote:
On Sat, 08 May 2004 23:19:51 -0400, Kevin Zhou <zr*****@hotmail.com>
wrote:

http://users.powernet.co.uk/eton/kandr2/krx414.html

#define swap(t,x,y) do{t z=x;x=y;y=z}while(0)

^;

#define SWAP(t, x, y) do{t z=(x); (x)=(y); (y)=z;}while(0)

SWAP(INT, x, y);
Nov 14 '05 #11
Kevin Zhou <zr*****@hotmail.com> wrote in message news:<c7**********@parasect.netlab.jp>...
The question is "define a macro swap(t,x,y) that interchanges two
arguments of type t".
What does it mean? what are arugments of a type? I can't find an
explanation in the book.


It means that the two arguments x and y have an undetermined type t.

I wrote some of the different macros on Richard Heathfield's site.
Here's a different solution I thought of that uses sizeof, so it's
category 1:

#define swap(t,x,y) myswap(sizeof(t),(unsigned char*)&(x),(unsigned
char*)&(y))
void myswap(unsigned long a,unsigned char *b,unsigned char *c)
{
while (a--) {
*b ^= *c;
*c ^= *b;
*b++ ^= *c++;
}
}

Gregory Pietsch
Nov 14 '05 #12
Gregory Pietsch wrote:
void myswap(unsigned long a,unsigned char *b,unsigned char *c)
Not size_t a?
{
while (a--) {
*b ^= *c;
*c ^= *b;
*b++ ^= *c++;
}
}


That's a really bad idea; not only does it fail to deal with the two
values being the same, but, should they share a single byte of their
respective representations, it has undesirable behaviour for the few
types where it's undefined at all.

--
++acr@,ka"
Nov 14 '05 #13
Sam Dennis <sa*@malfunction.screaming.net> wrote in message news:<sl****************@ID-227112.user.uni-berlin.de>...
Gregory Pietsch wrote:
void myswap(unsigned long a,unsigned char *b,unsigned char *c)
Not size_t a?


It probably comes later on in K&R2, or was a brain cramp on my fault. ;-)
{ if (b != c) while (a--) {
*b ^= *c;
*c ^= *b;
*b++ ^= *c++;
}
}


That's a really bad idea; not only does it fail to deal with the two
values being the same, but, should they share a single byte of their
respective representations, it has undesirable behaviour for the few
types where it's undefined at all.


Then how would you actually accomplish this?
Nov 14 '05 #14
Gregory Pietsch wrote:
Sam Dennis <sa*@malfunction.screaming.net> wrote in message news:<sl****************@ID-227112.user.uni-berlin.de>...
Gregory Pietsch wrote:
> void myswap(unsigned long a,unsigned char *b,unsigned char *c)


That's a really bad idea;


Then how would you actually accomplish this?


The same way as elsewhere in this thread (with intentional and
unintentional mistakes corrected): with a temporary variable.

--
++acr@,ka"
Nov 14 '05 #15
Sam Dennis <sa*@malfunction.screaming.net> wrote in message news:<sl****************@ID-227112.user.uni-berlin.de>...
Gregory Pietsch wrote:
Sam Dennis <sa*@malfunction.screaming.net> wrote in message news:<sl****************@ID-227112.user.uni-berlin.de>...
Gregory Pietsch wrote:
> void myswap(unsigned long a,unsigned char *b,unsigned char *c)

That's a really bad idea;


Then how would you actually accomplish this?


The same way as elsewhere in this thread (with intentional and
unintentional mistakes corrected): with a temporary variable.


So here's what you're telling me:

If the areas pointed to by b and c overlap, I should use a temporary
variable to swap the contents of b and c:

void myswap(size_t a, unsigned char *b, unsigned char *c)
{
unsigned char uc;

if (a && b && c)
while (a--) {
uc = *b;
*b = *c;
*c = uc;
b++, c++;
}
}

My point is that if the two areas overlap, you can't swap no matter
what algorithm you use. (Think about it for a second.)

Gregory Pietsch
Nov 14 '05 #16
Gregory Pietsch wrote:
> Sam Dennis <sa*@malfunction.screaming.net> wrote in message news:<sl****************@ID-227112.user.uni-berlin.de>...
>> Gregory Pietsch wrote:
>> > void myswap(unsigned long a,unsigned char *b,unsigned char *c)
>> > [xor bytewise]
>>
>> That's a really bad idea;


So here's what you're telling me:

If the areas pointed to by b and c overlap, I should use a temporary
variable to swap the contents of b and c:


Where did you get that from? What I'm trying to say is that the xor
hack is unreliable under the best of circumstances and that applying
it to object representations (of an unknown type, no less) is asking
for trouble.

If you absolutely need a function of this sort (for swapping arrays,
or somesuch, I guess), it's probably most efficient to have a buffer
local to the function of a reasonable size for a loop of three calls
to memcpy, analogous to the three assignments in a swapping macro.

What the hell would swapping objects that overlap mean, anyway? It's
utter nonsense!

--
++acr@,ka"
Nov 14 '05 #17

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

Similar topics

6
by: leonard greeff | last post by:
I want to know the correct way to answer exercise 1-11 of K&R. The only bug that I can find is that nw counts one to many words. (if there are 8 words, nw will be 9) Am I correct aor is there more...
46
by: Herrcho | last post by:
Hi~ i've studied C for a few months myself, and i'd appreciate it if anyone could improve my coding or correct it. the following is my solution to the K&R exercise 2-3 "Write the function...
12
by: Chris Readle | last post by:
Ok, I've just recently finished a beginning C class and now I'm working through K&R2 (alongside the C99 standard) to *really* learn C. So anyway, I'm working on an exercise in chapter one which...
12
by: Merrill & Michele | last post by:
It's very difficult to do an exercise with elementary tools. It took me about fifteen minutes to get exercise 1-7: #include <stdio.h> int main(int orange, char **apple) { int c; c=-5;...
8
by: Mike S | last post by:
Hi all, I noticed a very slight logic error in the solution to K&R Exercise 1-22 on the the CLC-Wiki, located at http://www.clc-wiki.net/wiki/KR2_Exercise_1-22 The exercise reads as...
16
by: Josh Zenker | last post by:
This is my attempt at exercise 1-10 in K&R2. The code looks sloppy to me. Is there a more elegant way to do this? #include <stdio.h> /* copies input to output, printing */ /* series of...
19
by: pkirk25 | last post by:
I wonder if anyone has time to write a small example program based on this data or to critique my own effort? A file called Realm List.html contains the following data: Bladefist-Horde...
19
by: arnuld | last post by:
this programme runs without any error but it does not do what i want it to do: ------------- PROGRAMME -------------- /* K&R2, section 1.6 Arrays; Exercise 1-13. STATEMENT: Write a program...
5
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any...
88
by: santosh | last post by:
Hello all, In K&R2 one exercise asks the reader to compute and print the limits for the basic integer types. This is trivial for unsigned types. But is it possible for signed types without...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.