473,441 Members | 1,813 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,441 software developers and data experts.

Programming Puzzle

I found these questions on a web site and wish to share with all of u
out there,Can SomeOne Solve these Porgramming puzzles.
Programming Puzzles

Some companies certainly ask for these things. Specially Microsoft.
Here are my favorite puzzles. Don't send me emails asking for the
solutions.

Q1 Write a "Hello World" program in 'C' without using a semicolon.
Q2 Write a C++ program without using any loop (if, for, while etc) to
print numbers from 1 to 100 and 100 to 1;
Q3 C/C++ : Exchange two numbers without using a temporary variable.
Q4 C/C++ : Find if the given number is a power of 2.
Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator.
Q6 C/C++ : Write a function in different ways that will return f(7) =
4 and f(4) = 7
Q7 Remove duplicates in array
Q8 Finding if there is any loop inside linked list.
Q9 Remove duplicates in an no key access database without using an
array
Q10 Write a program whose printed output is an exact copy of the
source. Needless to say, merely echoing the actual source file is not
allowed.
Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's),
each player selects a number and adds it to the total. Once a number
is used, it must be removed from the pool. The winner is the person
whose number makes the total equal 31 exactly.
Q12 Swap two numbers without using a third variable.
Given an array (group) of numbers write all the possible sub groups of
this group.
Q14 Convert (integer) number in binary without loops.

Q3,12 are similar , Q7 is simple & I know there answer For the Rest
please Help
Wiating for reply.
Nov 14 '05
271 19854
In <cb***********@ulysses.noc.ntua.gr> Ioannis Vranos <iv*@guesswh.at.grad.com> writes:
Dan Pop wrote:
Even under severe space concerns there is
always space for a *temporary* variable. If there are space concerns to
the extreme, then we should write numbers in its memory directly. :-)

Imagine that the universal swap function has the following interface:

void swap(void *p, void *q, size_t size);

What are you going to do if malloc(size) fails?


That is not much universal in my C++ world, since for non-POD types such
a generic function would invoke undefined behaviour.


Your C++ world is irrelevant once you cross-post to comp.lang.c.
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.


You must be a first class idiot if you *rely* on being able to use
a VLA of the same size as a failed malloc request. And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #151

"Dan Pop" <Da*****@cern.ch> wrote in message
news:cb**********@sunnews.cern.ch...
In <cb***********@ulysses.noc.ntua.gr> Ioannis Vranos <iv*@guesswh.at.grad.com> writes:
Dan Pop wrote:
Even under severe space concerns there is
always space for a *temporary* variable. If there are space concerns to
the extreme, then we should write numbers in its memory directly. :-)
Imagine that the universal swap function has the following interface:

void swap(void *p, void *q, size_t size);

What are you going to do if malloc(size) fails?
That is not much universal in my C++ world, since for non-POD types such
a generic function would invoke undefined behaviour.


Your C++ world is irrelevant once you cross-post to comp.lang.c.


Well, why the heck are you cross-posting to C++ if C++ is irrelevant?
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.
You must be a first class idiot if you *rely* on being able to use


This is the second time in a row you're resorted to insults. Care to keep
the discussion llimited to the subject?
a VLA of the same size as a failed malloc request. And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de

Nov 14 '05 #152
Dan Pop wrote:
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.

You must be a first class idiot if you *rely* on being able to use
a VLA of the same size as a failed malloc request.

For accuracy, I was talking about VLA with a small fixed size (instead
of a built in array), however VLAs are a mess so I would not use it
anyway (and also C99 is not one of my favourite standards).
And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.


Yes or single char ones.


Regards,

Ioannis Vranos
Nov 14 '05 #153
Risto Lankinen wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Please describe a situation where two variables share the same memory
location.


There is a doubly-linked-list algorithm that uses the same
memory location for both forward and backward pointers.
They are stored as XORred, and given the address of an
anchor node, the chain of nodes can be traversed at either
direction.

- Risto -


Could you please post the relevant code that sets up two variables that share
the same memory location?

Thanks
Nov 14 '05 #154
In <OQ********************@bgtnsc04-news.ops.worldnet.att.net> "Howard" <al*****@hotmail.com> writes:

"Dan Pop" <Da*****@cern.ch> wrote in message
news:cb**********@sunnews.cern.ch...
In <cb***********@ulysses.noc.ntua.gr> Ioannis Vranos

<iv*@guesswh.at.grad.com> writes:
>Dan Pop wrote:
>
>>>Even under severe space concerns there is
>>>always space for a *temporary* variable. If there are space concerns to
>>>the extreme, then we should write numbers in its memory directly. :-)
>>
>>
>> Imagine that the universal swap function has the following interface:
>>
>> void swap(void *p, void *q, size_t size);
>>
>> What are you going to do if malloc(size) fails?
>
>That is not much universal in my C++ world, since for non-POD types such
>a generic function would invoke undefined behaviour.


Your C++ world is irrelevant once you cross-post to comp.lang.c.


Well, why the heck are you cross-posting to C++ if C++ is irrelevant?


For the simple reason that C and C++ have a common subset and it is
perfectly possible to talk about swapping in the context of this common
subset.

If the OP wanted a discussion including the C++ features outside this
common subset s/he wouldn't have cross-posted to c.l.c in the first place.

Or am I missing something?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #155
In <cb***********@ulysses.noc.ntua.gr> Ioannis Vranos <iv*@guesswh.at.grad.com> writes:
Dan Pop wrote:
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.

You must be a first class idiot if you *rely* on being able to use
a VLA of the same size as a failed malloc request.

For accuracy, I was talking about VLA with a small fixed size (instead


What is a *variable* length array with a small *fixed* size? Looks like
an oxymoron to me...
of a built in array), however VLAs are a mess so I would not use it
anyway (and also C99 is not one of my favourite standards).


VLAs are far from being a mess. It's the availability of conforming C99
implementations that renders them useless for portable programming.
And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.


Yes or single char ones.


Nope, plain char is NOT exempt from trap representations. Furthermore,
even without trap representations, plain char can have padding bits and
a -0 may become a +0 when copied via a char on one's complement and
sign-magnitude implementations:

3 If the implementation supports negative zeros, they shall be
generated only by:

- the &, |, ^, ~, <<, and >> operators with arguments that
produce such a value;

- the +, -, *, /, and % operators where one argument is a negative
zero and the result is zero;

- compound assignment operators based on the above cases.

It is unspecified whether these cases actually generate a
negative zero or a normal zero, and whether a negative zero
^^^^^^^^^^^^^^^^^^^^^^^^^^^
becomes a normal zero when stored in an object.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

So, when thinking in terms of accessing value representations on a
byte by byte basis, the *one and only* type suitable for the job is
unsigned char: no padding bits, no trap representations, all values
from 0 to 2 ** CHAR_BIT - 1 represented in pure binary.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #156
Julie <ju***@nospam.com> wrote in message news:<40***************@nospam.com>...
Gordon Burditt wrote:
> >Not one, but *two* ways to do it have been
> >shown in this thread. Of course it will break down if those variables
> >happen to share the same memory location, which can be the case if using
> >pointers and indirecting through them.

Please describe (in code) a situation where two variables share the same memory
location.


A union?


Nope -- a union is still a single variable, with just different ways to access
it.

Could you please provide your preferred definition of "variable".
I wish to understand why you think a union member is not one.
Nov 14 '05 #157
Dan Pop wrote:

What is a *variable* length array with a small *fixed* size? Looks like
an oxymoron to me...

C++'s std::vector for example is of variable length, however usage in
the style:
vector<int> somearray(5);

is too common.
Nope, plain char is NOT exempt from trap representations. Furthermore,
even without trap representations, plain char can have padding bits and
a -0 may become a +0 when copied via a char on one's complement and
sign-magnitude implementations:


I do not know/have understood what "trap representations" actually are,
however in C++98 it is guaranteed to be safe to read POD types as
sequences of chars and unsigned chars:
"For any complete POD object type T, whether or not the object holds a
valid value of type T, the underlying bytes (1.7) making up the object
can be copied into an array of char or unsigned char.36) If the content
of the array of char or unsigned char is copied back into the object,
the object shall subsequently hold its original value.

[Example:

#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
memcpy(buf, &obj, N); // between these two calls to memcpy,
// obj might be modified
memcpy(&obj, buf, N); // at this point, each subobject of obj of
// scalar type
// holds its original value
—end example]

For any POD type T, if two pointers to T point to distinct T objects
obj1 and obj2, if the value of obj1 is copied into obj2, using the
memcpy library function, obj2 shall subsequently hold the same value as
obj1.

[Example:
T* t1p;
T* t2p;
// provided that t2p points to an initialized object ...
memcpy(t1p, t2p, sizeof(T)); // at this point, every subobject of POD
//type in *t1p contains
// the same value as the corresponding subobject in *t2p
—end example]"


Regards,

Ioannis Vranos
Nov 14 '05 #158
kal
Da*****@cern.ch (Dan Pop) wrote in message news:<cb**********@sunnews.cern.ch>...
In <2k***********@uni-berlin.de> "Alex Fraser" <me@privacy.net> writes:
"Dan Pop" <Da*****@cern.ch> wrote in message
news:cb***********@sunnews.cern.ch...
Consider, for example, 0 ^ 0, whose result (an int with all bits set)

[...]

*cough*


Indeed! A first class brain fart...


Ah! Merci beaucoup. I have been trying to understand that.
Nov 14 '05 #159
Dingo wrote:

Julie <ju***@nospam.com> wrote in message news:<40***************@nospam.com>...
Gordon Burditt wrote:

>> >Not one, but *two* ways to do it have been
>> >shown in this thread. Of course it will break down if those variables
>> >happen to share the same memory location, which can be the case if using
>> >pointers and indirecting through them.
>
>Please describe (in code) a situation where two variables share the same memory
>location.

A union?


Nope -- a union is still a single variable, with just different ways to access
it.

Could you please provide your preferred definition of "variable".
I wish to understand why you think a union member is not one.


I'll retract my statement -- I'll agree that a union does allow for two
variables to share the same memory address.
Nov 14 '05 #160
Da*****@cern.ch (Dan Pop) wrote in message news:<cb***********@sunnews.cern.ch>...
In <zo****************@newssvr27.news.prodigy.com> "Mabden" <mabden@sbc_global.net> writes:
"Foobarius Frobinium" <fo******@youremailbox.com> wrote in message
news:a7**************************@posting.google. com...
js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... You mentioned MS often use these sorts of puzzles to test their
programmers. I got an even better one to stump even the best MS
programmers:
#include <stdio.h>

int main(void) {
int *foo = NULL;

fprintf(stdout, "%i\n", *foo);
}

What will happen if I compile and run this program??
You'll get a warning saying main() has no return value.


Chapter and verse, please.


Well, you should, depending on compiler flags. gcc -Wall gives you:

foo.c: In function `main':
foo.c:10: warning: control reaches end of non-void function

Which is besides the point as I was making a joke about how shitty MS
programs are. Obviously, this will segfault.

Dan

Nov 14 '05 #161
In article <cb**********@oravannahka.helsinki.fi>,
Joona I Palaste <pa*****@cc.helsinki.fi> wrote:
Siemel Naran <Si*********@remove.att.net> scribbled the following
on comp.lang.c:
"Jerry Coffin" <jc*****@taeus.com> wrote in message
news:b2*************************@posting.google.co m...
Almost anything you'd normally do with iteration can also be done with
tail recursion.

What is "tail" recursion? Are there other types of recursion?


Tail recursion is first doing the computation, then recursing. Head
recursion is the other way around.


There's a generally-accepted definition that pins it down more precisely
than this.

A "tail call" is a call to a function where the return value of that
function is returned directly from the calling function without any
further processing:
--------
int foo(int i)
{
int j;
j=do_nontail_call(i);
return do_tail_call(j);
}
--------
(Or even:
--------
int foo2(int i)
{
return do_tail_call(do_nontail_call(i));
}
--------
which when untangled does the exact same thing, but doing the untangling
may lead to a clearer idea of where exactly the boundary is.)
It's possible, in theory at least (though some parameter passing
mechanisms make it too difficult to be worth the effort), to remove
the invocation record for the function making the tail call from the
invocation-record stack and have the tail-called function return directly
to the function that made the last non-tail function call.

"Tail recursion" is recursion accomplished using tail calls. Note that
this is a property of the calls made and not simply of the function
itself, and it's possible to make a tail-recursive and non-tail-recursive
call to the same function:
--------
void untested_and_probably_buggy_quicksort(int *data,size_t n)
{
int middle_index;

/*Make sure the recursion terminates*/
if(n<2)
return;

/*Hand-waving to avoid having to do too much thinking*/
middle_index=untested_and_probably_buggy_partition (data,n);

/*Non-tail-recursive call*/
untested_and_probably_buggy_quicksort(data,middle_ index-1);

/*Tail-recursive call*/
untested_and_probably_buggy_quicksort(data+middle_ index+1,
n-middle_index-1);
/*Note that even though we're not actually returning anything,
we're not doing anything between when the tail call returns
and when we return.
*/
}
--------
The aforementioned invocation-record-stack optimization for tail calls
has the effect of converting tail recursion into iteration, so the above
is exactly equivalent (assuming this optimization does indeed occur) to:
--------
void untested_and_probably_buggy_quicksort(int *data,size_t n)
{
int middle_index;

/*A compiler may not be clever enough to convert the exit
condition from the if(...)return form to while(...) directly,
but a good optimizer should generate the same code for
both forms.
*/
while(n>1)
{
/*These are the same as the tail-recursive version*/
middle_index=untested_and_probably_buggy_partition (data,n);
untested_and_probably_buggy_quicksort(data,middle_ index-1);

/*Here we're replacing the old parameters with the values
they'd have in the next (tail-recursive) invocation,
then going back to the top of the loop
*/
data=data+middle_index+1;
n=n-middle_index-1;
}
}
--------
dave

--
Dave Vandervies dj******@csclub.uwaterloo.ca
[Knuth] writes that some authors have declared the method optimal, but he is
kind enough to spare them embarrassment by omitting their names; clearly they
forgot to consider cases like n==15. --Eric Sosman in comp.lang.c
Nov 14 '05 #162
>> #include "card_t.h" /* This is part of the program, NOT the
#implementation*/ define DECKSIZE 52
...
int i,j;
card_t deck[DECKSIZE];

/* bogo-shuffle the cards */
for (i = 0; i < DECKSIZE; i++) {
for (j = 0; j < DECKSIZE; j++) {
/*
* DO NOT CHANGE THE LINE OF CODE BELOW.
* Note: rand() % 2 is used here because it is
* a poor random number generator in many
* implementations, and if it isn't possible to
* cheat, *THEY* will break your legs repeatedly
* and cut off your supply of semicolons.
*/
if (rand() % 2) {
swap(&deck[i], &deck[j]);
}
}
}

Hi,

I apologize, for this might not be the topic of this thread, however I feel
compelled to comment on this bogo-shuffle: is that taken from a text on how
*not* to generate a random permutation?


No, it was not taken from a text. It is original code written for
the post. I needed an excuse for why I might want to swap two
elements of an array, possibly even if they happen to be the same
element.
a) The use of rand() % 2 is bad. In a different thread I came across a
random number generator that would produce a strictly alternating sequence
of bits when used this way. The funny comment indicates that the author was
acutally aware of this shortcoming.
An implementation of rand() can SUCK(tm) without producing a strictly
alternating sequence of bits, although it's hard to make it suck
strictly worse than that (I suppose always returning 1 or always
returning zero qualifies as sucking worse, though). Why do you
think the comment was in there?
b) The method has quadratic runtime in DECKSIZE. Clearly a random-shuffle
can and should be done in linear time.
Clearly a performance criteria for a method does not have to specify
a MAXIMUM runtime; sometimes it is desired for performance to be
at least so BAD and worse is possible (for example, making the
algorithm HARD to implement efficiently was one concern in the
original design of UNIX password encryption). Another example is
the use of 16 nested infinite loops where a single infinite loop
would do.
c) Finally, even with a perfect random number generator, this method is
guaranteed *not* to give equal probabilities to the different permutations.
For small DECKSIZE, the difference is even noticable.


A bogosort sorts by generating all possible permutations of the
input, then (bubble) sorting the permutations by the number of
elements out of order, and returning the one with the least number
of elements out of order. In other words, it replaces the job of
sorting N elements to one of sorting N! elements. A recursive
bogosort uses bogosort instead of bubble sort to sort the permutations,
thus replacing the job of sorting N elements with one of sorting
N!!!!!!!!!!!!!!!!!!!!!!!!!!!! ... It is also likely to cause the
heat death of at least 2**(N!) universes before it finishes (by
crashing due to trying to use more memory than there are particles
in the universe).

A bogo-shuffle, named after bogosort, is a poorly-implemented, SLOW
shuffle but it doesn't come close to the inefficiency of the recursive
bogosort. You probably won't ever get to use it enough to discover
that the probabilities aren't equal. Nobody lives that long.

Gordon L. Burditt
Nov 14 '05 #163
Jim
On Mon, 28 Jun 2004 13:48:36 -0700, Julie <ju***@nospam.com> wrote:
Howard wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...
> Howard wrote:

> Break given.


Thanks! :-)
>
> Your example doesn't swap two integers, it swaps one.
>
> I know exactly what is meant -- using the xor technique on two variables

will
> never fail; using the xor technique on the same variable (same literal
> variable, reference, or pointer -- still all *ONE* variable) will fail for

most
> cases.
>
> You have given example(s) of the latter, *not* the former. There is no
> disagreement on the latter.


There is no disagreement on the former, either. Just a difference in the
wording of the problem. To me, two pointers or references that refer to the
same memory location are still two differrent variables. But you are
correct...the memory locations being swapped in such a case are identical,
thus you could rightfuly call them "the same".

The importance, though, as it relates to actually *writing* a swap function,
is that the swap function itself cannot guarantee in advance that the
reference or pointer parameters passed into it will not at some point refer
to the same location in memory. Therefore, it is vital that such a swap
function include a guard against swapping the "same" variable. (Unless, of
course, you clearly document that the function does *not* guard against such
behavior, and declare such usage of the function as a violation of its
contract, generating undefined behavior.)

-Howard


Agreed.

For me, saying that 'swap operates on two variables' would be sufficient, but
for the sake of clarity, it could be documented that references to the same
variable leads to undefined behavior.


Isn't this exectly what C99's 'restrict' type qualifier is for?

Jim
Nov 14 '05 #164
On Mon, 28 Jun 2004 04:16:52 +0300, Ioannis Vranos wrote:
Jatinder wrote:

Ok I couldn't resist so I 'll give my answers to these questions. As a
poster has done previously, where "C" is mentioned I consider C++98 (I
view these from clc++).


Me neither.
> Q2 Write a C++ program without using any loop (if, for, while etc) to
> print numbers from 1 to 100 and 100 to 1;

Note: There is a restriction for if statements, but if statements do not
constitute a loop.

<snip recursive version>

I suspect what they meant was something of this sort:

#include <iostream>

template <int i> class Count
{
Count<i-1> c;
public:
Count() : c() { std::cout << i << std::endl; }
};

template <> class Count<1>
{
public:
Count() { std::cout << "1" << std::endl; }
};

int main(void)
{
Count<100> c;
return 0;
}

With a modification to count back down.

Tim.
Nov 14 '05 #165

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Could you please post the relevant code that sets up two variables that share the same memory location?


This is a good start:

http://groups.google.fi/groups?selm=...y.DIALix.oz.au

- Risto -
Nov 14 '05 #166
Julie wrote:
Please describe (in code) a situation where two
variables share the same memory location.


In post
http://groups.google.com/groups?selm...mindspring.com
in the function n_sort, the variable (*node),
has the same address as either (tail) or (head) after this line:

node = GT(head, tail) ? &tail : &head;

--
pete
Nov 14 '05 #167
In <a7**************************@posting.google.com > fo******@youremailbox.com (Foobarius Frobinium) writes:
Da*****@cern.ch (Dan Pop) wrote in message news:<cb***********@sunnews.cern.ch>...
In <zo****************@newssvr27.news.prodigy.com> "Mabden" <mabden@sbc_global.net> writes:
>"Foobarius Frobinium" <fo******@youremailbox.com> wrote in message
>news:a7**************************@posting.google. com...
>> js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>...
>> You mentioned MS often use these sorts of puzzles to test their
>> programmers. I got an even better one to stump even the best MS
>> programmers:
>> #include <stdio.h>
>>
>> int main(void) {
>> int *foo = NULL;
>>
>> fprintf(stdout, "%i\n", *foo);
>> }
>>
>> What will happen if I compile and run this program??
>
>You'll get a warning saying main() has no return value.


Chapter and verse, please.


Well, you should, depending on compiler flags.


Sez who?
gcc -Wall gives you:

foo.c: In function `main':
foo.c:10: warning: control reaches end of non-void function


Add a -std=c99 to your gcc invocation and the warning goes away.

My point was that it is sheer nonsense to say "you'll get a warning about
that" if the standard doesn't *require* a diagnostic.

I entirely agree that the code deserves a diagnostic, even when compiled
in C99 mode, but this is something completely different.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #168
In <40***************@nospam.com> Julie <ju***@nospam.com> writes:
Dingo wrote:

Julie <ju***@nospam.com> wrote in message news:<40***************@nospam.com>...
> Gordon Burditt wrote:
> >
> > >> >Not one, but *two* ways to do it have been
> > >> >shown in this thread. Of course it will break down if those variables
> > >> >happen to share the same memory location, which can be the case if using
> > >> >pointers and indirecting through them.
> > >
> > >Please describe (in code) a situation where two variables share the same memory
> > >location.
> >
> > A union?
>
> Nope -- a union is still a single variable, with just different ways to access
> it.

Could you please provide your preferred definition of "variable".
I wish to understand why you think a union member is not one.


I'll retract my statement -- I'll agree that a union does allow for two
variables to share the same memory address.


And, if you think even harder, you'll realise that it's the same thing
with pointers: *p and *q are two different variables, but they may share
the same memory address, depending on how the p and q variables have been
initialised (e.g. one may be pointing to one member of the union, the
other may be pointing to the other member of the union mentioned in the
union example :-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #169
In <cb**********@ulysses.noc.ntua.gr> Ioannis Vranos <iv*@guesswh.at.grad.com> writes:
Dan Pop wrote:

What is a *variable* length array with a small *fixed* size? Looks like
an oxymoron to me...


C++'s std::vector for example is of variable length, however usage in
the style:

vector<int> somearray(5);

is too common.


Which has nothing to do with *your* usage of the term VLA, which has a
very well defined meaning in C99.
Nope, plain char is NOT exempt from trap representations. Furthermore,
even without trap representations, plain char can have padding bits and
a -0 may become a +0 when copied via a char on one's complement and
sign-magnitude implementations:


I do not know/have understood what "trap representations" actually are,
however in C++98 it is guaranteed to be safe to read POD types as
sequences of chars and unsigned chars:


It doesn't matter: in the common subset of the two languages, it is
*always* the most restrictive language that "wins".

However, if C++ allows one's complement and sign-magnitude, the guarantees
about plain char are a lie: because -0 and +0 are different
representations of the *same* value and you're effectively losing
information when reading a byte through a plain char: bytes with all
bits zero and bytes with all bits one will be read as having the *same*
value. And if you copy this value to another place, you have no guarantee
that the same representation will be used.

That is, assuming that plain char has the same semantics in both
languages: a type *different* from both signed char and unsigned char, but
sharing the semantics of one of them.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #170
Dan Pop wrote in news:cb***********@sunnews.cern.ch in comp.lang.c++:
However, if C++ allows one's complement and sign-magnitude, the
guarantees about plain char are a lie: because -0 and +0 are different
representations of the *same* value and you're effectively losing
information when reading a byte through a plain char: bytes with all
bits zero and bytes with all bits one will be read as having the
*same* value. And if you copy this value to another place, you have
no guarantee that the same representation will be used.

In C++ plain char is allowed to have the same representation and
symantics as unsigned char.

Its required that char and unsigned char be usable as "raw-memory".

Conclusion: on a one's compliment/signed magnitude machine char has
the same representation and symantics as unsigned char.
That is, assuming that plain char has the same semantics in both
languages: a type *different* from both signed char and unsigned char,
but sharing the semantics of one of them.


Yes.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Nov 14 '05 #171
ld
Ioannis Vranos wrote:
Ioannis Vranos wrote:
Jatinder wrote:
Q3 C/C++ : Exchange two numbers without using a temporary variable.



Isn't the bitwise solution safe only for unsigned integrals?


I just checked the standard, it is safe for both integral and
enumeration types.

....but it definitely is a nonsense for floating point numbers.
Therefore, there's no general way how to "Exchange two numbers without
using a temporary variable."

ld
Nov 14 '05 #172
ld
Julie wrote:
Joona I Palaste wrote:
Of course it will break down if those variables
happen to share the same memory location, which can be the case if using
pointers and indirecting through them.

Explain to me how *two* variables can share the same memory address.


say please
Nov 14 '05 #173
Dan Pop wrote:

In <40***************@nospam.com> Julie <ju***@nospam.com> writes:
Dingo wrote:

Julie <ju***@nospam.com> wrote in message news:<40***************@nospam.com>...
> Gordon Burditt wrote:
> >
> > >> >Not one, but *two* ways to do it have been
> > >> >shown in this thread. Of course it will break down if those variables
> > >> >happen to share the same memory location, which can be the case if using
> > >> >pointers and indirecting through them.
> > >
> > >Please describe (in code) a situation where two variables share the same memory
> > >location.
> >
> > A union?
>
> Nope -- a union is still a single variable, with just different ways to access
> it.
Could you please provide your preferred definition of "variable".
I wish to understand why you think a union member is not one.


I'll retract my statement -- I'll agree that a union does allow for two
variables to share the same memory address.


And, if you think even harder, you'll realise that it's the same thing
with pointers: *p and *q are two different variables, but they may share
the same memory address, depending on how the p and q variables have been
initialised (e.g. one may be pointing to one member of the union, the
other may be pointing to the other member of the union mentioned in the
union example :-)


Negative. I do not consider pointers or references that point to the same
variable to *be* the same variable. In your example, yes _p_ and _q_ are
variables, _*p_ and _*q_ are not, they merely (may) point to 0 or more
variables.
Nov 14 '05 #174
In <a5**************************@posting.google.com > k_*****@yahoo.com (kal) writes:
Da*****@cern.ch (Dan Pop) wrote in message news:<cb**********@sunnews.cern.ch>...
In <2k***********@uni-berlin.de> "Alex Fraser" <me@privacy.net> writes:
>"Dan Pop" <Da*****@cern.ch> wrote in message
>news:cb***********@sunnews.cern.ch...
>> Consider, for example, 0 ^ 0, whose result (an int with all bits set)
>[...]
>
>*cough*


Indeed! A first class brain fart...


Ah! Merci beaucoup. I have been trying to understand that.


There is no shame in asking when you don't understand something...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #175
Risto Lankinen wrote:

"Julie" <ju***@nospam.com> wrote in message
news:40***************@nospam.com...

Could you please post the relevant code that sets up two variables that

share
the same memory location?


This is a good start:

http://groups.google.fi/groups?selm=...y.DIALix.oz.au


Wha?! Forth? I don't see anything that even remotely describes how to set up
two variables that share the same memory location (_in_C_or_C++_, please).

When posting links, it is _most_ helpful if you first quote the relevant
portion(s), then post the referencing link...

Try again?
Nov 14 '05 #176
pete wrote:

Julie wrote:
Please describe (in code) a situation where two
variables share the same memory location.


In post
http://groups.google.com/groups?selm...mindspring.com
in the function n_sort, the variable (*node),
has the same address as either (tail) or (head) after this line:

node = GT(head, tail) ? &tail : &head;


Try again.

No *variable* is sharing the same address. Node, head, and tail all have
different addresses, unless you can say that any of the following is true:

&node == &head == &tail

It doesn't matter what node _points_ to, it matters where node _is_.

Under your logic, the following two variables:

int a = 1;
int b = 2;

become the _same_ same variable with the following:

b = 1;

Surely you don't now consider a and b the same _variable_, do you?

Remember, we are talking about _addresses_ of variables, not the _value_ of
variables.
Nov 14 '05 #177

Haven't we beaten this dead horse long enough???

-Howard
Nov 14 '05 #178
Howard wrote:

Haven't we beaten this dead horse long enough???

-Howard


No, just getting started.

Those that are not interested in the outcome or further discussion of this
topic/thread, are welcome to ignore the thread in their newsreader. In
Netscape (4.x), press 'K' and you will not be bothered any more w/ our
senseless blather on swapping and the (dis)similarity of variable addresses.
Nov 14 '05 #179
Julie posted:
Howard wrote:

Haven't we beaten this dead horse long enough???

-Howard


No, just getting started.

Those that are not interested in the outcome or further discussion of
this topic/thread, are welcome to ignore the thread in their
newsreader. In Netscape (4.x), press 'K' and you will not be bothered
any more w/ our senseless blather on swapping and the (dis)similarity
of variable addresses.


I'm a variable.
-JKop
Nov 14 '05 #180
Julie wrote:
Howard wrote:

Haven't we beaten this dead horse long enough???

-Howard


No, just getting started.

Those that are not interested in the outcome or further discussion of this
topic/thread, are welcome to ignore the thread in their newsreader. In
Netscape (4.x), press 'K' and you will not be bothered any more w/ our
senseless blather on swapping and the (dis)similarity of variable
addresses.


Hi,
may I offer a tentative definition for the term "variable" that hopefully
describes the way I use the term: To me a variable is a textual
representation of an lvalue within a piece of source code. The lvalue
condition distinguishes variables from arbitrary expressions. A variable
can change its value, and the basic means of accomplishing that is the
assignment. For instance, I consider "*p" a variable whenever "p" deontes a
pointer to something non-const.

It is clear from the definition I gave that there can be literally
thousands of variables that refer to the same memory location.

What is your prefered definition of variable?
Best

Kai-Uwe Bux
Nov 14 '05 #181
In <cb***********@ns.felk.cvut.cz> ld <do*****@control.felk.cvut.cz> writes:
Ioannis Vranos wrote:
Ioannis Vranos wrote:
Jatinder wrote:

Q3 C/C++ : Exchange two numbers without using a temporary variable.

Isn't the bitwise solution safe only for unsigned integrals?


I just checked the standard, it is safe for both integral and
enumeration types.

...but it definitely is a nonsense for floating point numbers.
Therefore, there's no general way how to "Exchange two numbers without
using a temporary variable."


Wrong! The values of two objects of *any* type can be exchanged on
a byte by byte basis, without using a temporary variable. Is that
general enough for you?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #182
In <40***************@nospam.com> Julie <ju***@nospam.com> writes:
Dan Pop wrote:

In <40***************@nospam.com> Julie <ju***@nospam.com> writes:
>Dingo wrote:
>>
>> Julie <ju***@nospam.com> wrote in message news:<40***************@nospam.com>...
>> > Gordon Burditt wrote:
>> > >
>> > > >> >Not one, but *two* ways to do it have been
>> > > >> >shown in this thread. Of course it will break down if those variables
>> > > >> >happen to share the same memory location, which can be the case if using
>> > > >> >pointers and indirecting through them.
>> > > >
>> > > >Please describe (in code) a situation where two variables share the same memory
>> > > >location.
>> > >
>> > > A union?
>> >
>> > Nope -- a union is still a single variable, with just different ways to access
>> > it.
>> Could you please provide your preferred definition of "variable".
>> I wish to understand why you think a union member is not one.
>
>I'll retract my statement -- I'll agree that a union does allow for two
>variables to share the same memory address.
And, if you think even harder, you'll realise that it's the same thing
with pointers: *p and *q are two different variables, but they may share
the same memory address, depending on how the p and q variables have been
initialised (e.g. one may be pointing to one member of the union, the
other may be pointing to the other member of the union mentioned in the
union example :-)


Negative.


I see: I was pushing your thinking capabilities too hard ;-)
I do not consider pointers or references that point to the same
variable to *be* the same variable. In your example, yes _p_ and _q_ are
variables, _*p_ and _*q_ are not, they merely (may) point to 0 or more
variables.


Wrongo! *p and *q don't point to anything (unless p and q are pointers to
pointers), they are as "variables" as you can get. It is p and q that
point to variables.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #183
Julie <ju***@nospam.com> wrote:
pete wrote:

Julie wrote:
> Please describe (in code) a situation where two
> variables share the same memory location.


In post
http://groups.google.com/groups?selm...mindspring.com
in the function n_sort, the variable (*node),
has the same address as either (tail) or (head) after this line:

node = GT(head, tail) ? &tail : &head;


Try again.

No *variable* is sharing the same address. Node, head, and tail all have
different addresses, unless you can say that any of the following is true:

&node == &head == &tail

It doesn't matter what node _points_ to, it matters where node _is_.

Under your logic, the following two variables:

int a = 1;
int b = 2;

become the _same_ same variable with the following:

b = 1;

Surely you don't now consider a and b the same _variable_, do you?

Remember, we are talking about _addresses_ of variables, not the _value_ of
variables.


<my two cents>

1. Technically, the discussion is about objects, identifiers that
designate/denote objects (aka variable names in C++), and values.

2. Julie is right, insofar as no two distinct identifiers can
designate the same object - with the obvious exception of union
members, but consider: union { int a, b; } u, *up = &u;
Now u.a, u.b, up->a and up->b denote the same object, but they are
*not* identifiers that denote objects, but expressions consisting
of two operands and one operator each. The member designators a
and b cannot be used in their own right to denote an object, they
can only appear as second operand of the . or -> operator.

3. The others are right, in that two pointer objects can reference the
same memory location (= have the same value, just like two ints
can hold equal values). This however has no bearing on the "swap a
variable with itself" issue: swapping the pointer values won't work
portably with XOR anyway, and using indirection to access the
pointed-to object involves an expression that is *not* a variable.

4. The infamous "swap with XOR" method has not only limitations WRT
the type of the operands[*], it's also broken by design, because
it fails to correctly swap the value of an object (sic!) with
itself.

5. I suggest to drop the term "variable" all together, *especially* in
cross-posts between c.l.c and c.l.c++, since it's not defined at
all in the C standard and IMHO somewhat vaguely defined in the C++
standard.

[*] Modulo accessing the representation of each operand byte-per-byte
through a pointers to unsigned char.

</my two (actually five ;-) cents>

Regards
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc OT guide : http://benpfaff.org/writings/clc/off-topic.html
Nov 14 '05 #184
Dan Pop wrote:

In <40***************@nospam.com> Julie <ju***@nospam.com> writes:
Dan Pop wrote:

In <40***************@nospam.com> Julie <ju***@nospam.com> writes:

>Dingo wrote:
>>
>> Julie <ju***@nospam.com> wrote in message news:<40***************@nospam.com>...
>> > Gordon Burditt wrote:
>> > >
>> > > >> >Not one, but *two* ways to do it have been
>> > > >> >shown in this thread. Of course it will break down if those variables
>> > > >> >happen to share the same memory location, which can be the case if using
>> > > >> >pointers and indirecting through them.
>> > > >
>> > > >Please describe (in code) a situation where two variables share the same memory
>> > > >location.
>> > >
>> > > A union?
>> >
>> > Nope -- a union is still a single variable, with just different ways to access
>> > it.
>> Could you please provide your preferred definition of "variable".
>> I wish to understand why you think a union member is not one.
>
>I'll retract my statement -- I'll agree that a union does allow for two
>variables to share the same memory address.

And, if you think even harder, you'll realise that it's the same thing
with pointers: *p and *q are two different variables, but they may share
the same memory address, depending on how the p and q variables have been
initialised (e.g. one may be pointing to one member of the union, the
other may be pointing to the other member of the union mentioned in the
union example :-)


Negative.


I see: I was pushing your thinking capabilities too hard ;-)
I do not consider pointers or references that point to the same
variable to *be* the same variable. In your example, yes _p_ and _q_ are
variables, _*p_ and _*q_ are not, they merely (may) point to 0 or more
variables.


Wrongo! *p and *q don't point to anything (unless p and q are pointers to
pointers), they are as "variables" as you can get. It is p and q that
point to variables.


We disagree.
Nov 14 '05 #185
>> > > >Please describe (in code) a situation where two variables share
the same memory
> > >location.
> >
> > A union?
>
> Nope -- a union is still a single variable, with just different waysto access > it.

Could you please provide your preferred definition of "variable".
I wish to understand why you think a union member is not one.


I'll retract my statement -- I'll agree that a union does allow for two
variables to share the same memory address.


Could you please provide your definition of "variable"?

I'll provide mine: modifiable lvalue.

By this definition, these are variables:

foo.a (where foo is a struct or union)
foo[1] (where foo is an array of dimension at least 2)
foo[j] (where foo is an array, and j is in range)
foo[k] (where foo is an array, and k is in range)

AND, I'll claim that foo[j] and foo[k] are variables, and they
are usually different variables (occupy different memory), but
they could refer to the same memory if j == k.

Gordon L. Burditt
Nov 14 '05 #186
Ioannis Vranos <iv*@guesswh.at.grad.com> wrote in message news:<cb***********@ulysses.noc.ntua.gr>...
int main (void)
{
if (printf("Hello World")) {}

/* Only needed for C90 compliance */
if (exit(EXIT_SUCCESS),1){}
}


Here was my less elegant solution. But I didn't even use anything that
looks like a ';'. (commas look a lot like semicolons...) :)

#include <stdio.h>
#include <stdlib.h>

int main() {
while(printf("hello\n") && 0) {
}
while(((int (*)(int))(exit))(0) || 1) {}
}
Nov 14 '05 #187
"xarax" <xa***@email.com> wrote in message news:<cv******************@newsread2.news.pas.eart hlink.net>...
Those BS interviews asking about how to twiddle bits are a
waste of time. If I can't recall an exact algorithm, I just
look it up in one of my many reference books, including the
3 volumes of Knuth. The overall approach to solving a problem
and how I think about designing a solution is what's really
important. Don't sweat the small things, that's what junior
programmers are for.


When an interviewer uses these types of questions correctly they are
trying to see how you think. They aren't looking for the exact (or
even a correct) answer or exact syntax, but that you understand the
fundamentals the question is based on and that you can reason through
problems. Getting the right answer isn't the point.

Unfortunately these types of questions are often abused by people who
don't know how to interview. And if they don't ask anything but
bit-twiddler questions that's also a problem.
Nov 14 '05 #188
In article <jk********************************@4ax.com> ir*******@freenet.de writes:
Julie <ju***@nospam.com> wrote: ....
No *variable* is sharing the same address. Node, head, and tail all have
different addresses, unless you can say that any of the following is true:

.... 1. Technically, the discussion is about objects, identifiers that
designate/denote objects (aka variable names in C++), and values.


Technically the case hinges on the definition of "variable", which C does
not give. Let Julie show the implementation of a swap function of two
"variables" in C, and after that we can look further.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #189
"Dik T. Winter" wrote:

In article <jk********************************@4ax.com> ir*******@freenet.de writes:
> Julie <ju***@nospam.com> wrote:

...
> >No *variable* is sharing the same address. Node, head, and tail all have
> >different addresses, unless you can say that any of the following is true:

...
> 1. Technically, the discussion is about objects, identifiers that
> designate/denote objects (aka variable names in C++), and values.


Technically the case hinges on the definition of "variable", which C does
not give. Let Julie show the implementation of a swap function of two
"variables" in C, and after that we can look further.


Actually, the original says "two numbers" -- it disintegrated into 'show me two
variables that have the same memory location' soon afterward.

It has been shown that two variables can have have the same memory location
using unions. Therefore, in order to successfully use the XOR swap trick, the
precondition needs to be: uses two variables that do not share the same
address.

-end
Nov 14 '05 #190
Da*****@cern.ch (Dan Pop) wrote in message news:<cb**********@sunnews.cern.ch>...

<snip>
My point was that it is sheer nonsense to say "you'll get a warning about
that" if the standard doesn't *require* a diagnostic.
It is one thing to point out what the standard says, what messages
should be there, etc. It is another thing to get into a harsh argument
about it with someone else.

I entirely agree that the code deserves a diagnostic, even when compiled
in C99 mode, but this is something completely different.

Dan

Nov 14 '05 #191
"Dan Pop" <Da*****@cern.ch> wrote in message
news:cb**********@sunnews.cern.ch...
In <a7**************************@posting.google.com > fo******@youremailbox.com (Foobarius Frobinium) writes:
Da*****@cern.ch (Dan Pop) wrote in message news:<cb***********@sunnews.cern.ch>...
In <zo****************@newssvr27.news.prodigy.com> "Mabden" <mabden@sbc_global.net> writes:
>"Foobarius Frobinium" <fo******@youremailbox.com> wrote in message
>news:a7**************************@posting.google. com...
>> js*******@sancharnet.in (Jatinder) wrote in message
news:<22**************************@posting.google. com>...
>> You mentioned MS often use these sorts of puzzles to test their
>> programmers. I got an even better one to stump even the best MS
>> programmers:
>> #include <stdio.h>
>>
>> int main(void) {
>> int *foo = NULL;
>>
>> fprintf(stdout, "%i\n", *foo);
>> }
>>
>> What will happen if I compile and run this program??
>
>You'll get a warning saying main() has no return value.

Chapter and verse, please.


Well, you should, depending on compiler flags.


Sez who?
gcc -Wall gives you:

foo.c: In function `main':
foo.c:10: warning: control reaches end of non-void function


Add a -std=c99 to your gcc invocation and the warning goes away.

My point was that it is sheer nonsense to say "you'll get a warning about
that" if the standard doesn't *require* a diagnostic.

I entirely agree that the code deserves a diagnostic, even when compiled
in C99 mode, but this is something completely different.


Actually, it is the OP's question that I answered.

Let me help you out be repeating the question and answer for you, Dan.
Q. "What will happen if I compile and run this program??"
A. "You'll get a warning saying main() has no return value."

Do you see a question about standards or committees? No, just "what will
happen". So I showed a specific case of what would happen. Others have
reported their results of what happened.

Theory was not requested, not a specific implementation. On my box, that is
what will happen.

YMMV! ;-) Lighten up, Dan.

--
Mabden
Nov 14 '05 #192
In <nV*******************@newssvr29.news.prodigy.co m> "Mabden" <mabden@sbc_global.net> writes:
"Dan Pop" <Da*****@cern.ch> wrote in message
news:cb**********@sunnews.cern.ch...
In <a7**************************@posting.google.com >fo******@youremailbox.com (Foobarius Frobinium) writes:
>Da*****@cern.ch (Dan Pop) wrote in messagenews:<cb***********@sunnews.cern.ch>... >> In <zo****************@newssvr27.news.prodigy.com> "Mabden"<mabden@sbc_global.net> writes: >>
>> >"Foobarius Frobinium" <fo******@youremailbox.com> wrote in message
>> >news:a7**************************@posting.google. com...
>> >> js*******@sancharnet.in (Jatinder) wrote in message
>> news:<22**************************@posting.google. com>...
>> >> You mentioned MS often use these sorts of puzzles to test their
>> >> programmers. I got an even better one to stump even the best MS
>> >> programmers:
>> >> #include <stdio.h>
>> >>
>> >> int main(void) {
>> >> int *foo = NULL;
>> >>
>> >> fprintf(stdout, "%i\n", *foo);
>> >> }
>> >>
>> >> What will happen if I compile and run this program??
>> >
>> >You'll get a warning saying main() has no return value.
>>
>> Chapter and verse, please.
>
>Well, you should, depending on compiler flags.


Sez who?
>gcc -Wall gives you:
>
>foo.c: In function `main':
>foo.c:10: warning: control reaches end of non-void function


Add a -std=c99 to your gcc invocation and the warning goes away.

My point was that it is sheer nonsense to say "you'll get a warning about
that" if the standard doesn't *require* a diagnostic.

I entirely agree that the code deserves a diagnostic, even when compiled
in C99 mode, but this is something completely different.


Actually, it is the OP's question that I answered.

Let me help you out be repeating the question and answer for you, Dan.
Q. "What will happen if I compile and run this program??"
A. "You'll get a warning saying main() has no return value."

Do you see a question about standards or committees? No, just "what will
happen". So I showed a specific case of what would happen. Others have
reported their results of what happened.


The OP question was generic! He didn't ask "what will happen if *you*
compile and run this program?", did he? You can't provide an equally
generic answer based on the behaviour of your compiler. Such an answer
must be based on the C language definition.

Furthermore, the specific behaviour of one compiler or another is usually
considered off topic in this newsgroup, you need a *good* reason for
invoking your compiler's behaviour.
Theory was not requested, not a specific implementation. On my box, that is
what will happen. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Did the OP ask what will happen on *your* box? If not, what *exactly* is
your point, especially since you're admitting yourself that the question
was not about a specific implementation?
YMMV! ;-) Lighten up, Dan.


Stop behaving like an idiot and I'll lighten up ;-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #193
In <c3**************************@posting.google.com > sc************@comcast.net (Scott Jacobsen) writes:
Ioannis Vranos <iv*@guesswh.at.grad.com> wrote in message news:<cb***********@ulysses.noc.ntua.gr>...
int main (void)
{
if (printf("Hello World")) {}

/* Only needed for C90 compliance */
if (exit(EXIT_SUCCESS),1){}
}
Here was my less elegant solution. But I didn't even use anything that
looks like a ';'. (commas look a lot like semicolons...) :)

#include <stdio.h>
#include <stdlib.h>

int main() {
while(printf("hello\n") && 0) {
}
while(((int (*)(int))(exit))(0) || 1) {}

^^^^^^^^^^^^^^^^^^^^^^^^^
Undefined behaviour. You can convert the address of exit to an
incompatiple function pointer type, but you cannot dereference the
result without invoking undefined behaviour. Your code is akin to
calling exit() without including <stdlib.h> in C89: you can't call
a void function as if it were an int function.

It is not possible to call a void function in such a program without
using the comma operator. Fortunately, no C or C++ standard requires
the function main to terminate through an exit call or a return statement.
}


Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #194
Ioannis Vranos wrote:

That said, I would not place the equality/inequality check for the
possibility of the same variable passed in mind, but for efficiency.


If you have efficiency in mind, you better leave out the comparison
until tests show that the 'problem' it solves really happens that
often, that it makes a difference.

In any ordinary program one would not expect that special case to
happen very often. I would estimate around 1 out of 100 where this
'optimization' shortcut really is taken. That means: you slow down
99 cases just to speed up 1 case.

Same with the comparison for equality in an operator= (Sorry for
being off topic in comp.lang.c). If it is written exception safe,
there is no need for the test with 'this'. Especially not for
optimizaztion, since the case you are optimizing doesn't happen
that often in any typical program. But all other cases suffer
from a needless comparison.

--
Karl Heinz Buchegger
kb******@gascad.at
Nov 14 '05 #195
In <jk********************************@4ax.com> Irrwahn Grausewitz <ir*******@freenet.de> writes:
<my two cents>

1. Technically, the discussion is about objects, identifiers that
designate/denote objects (aka variable names in C++), and values.
Nope, the discussion was about "variables".
5. I suggest to drop the term "variable" all together, *especially* in
cross-posts between c.l.c and c.l.c++, since it's not defined at
all in the C standard and IMHO somewhat vaguely defined in the C++
standard.


As long as c.l.c is still an imperfect ivory tower (i.e. it still has
connections with the real world) it is highly unrealistic to ignore
popular CS jargon terms like "variable" and "global", simply because the
C standard itself doesn't use them.

By the time c.l.c is officially decreed a select club of initiated
regulars, there would be no need to ban these terms, because no one would
use them, anyway.

I guess similar considerations apply to c.l.c++...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #196
Dan Pop wrote:
In <c3**************************@posting.google.com >
sc************@comcast.net (Scott Jacobsen) writes:
Here was my less elegant solution. But I didn't even use anything that
looks like a ';'. (commas look a lot like semicolons...) :)

#include <stdio.h>
#include <stdlib.h>

int main() {
while(printf("hello\n") && 0) {
}
while(((int (*)(int))(exit))(0) || 1) {}

^^^^^^^^^^^^^^^^^^^^^^^^^
Undefined behaviour. You can convert the address of exit to an
incompatiple function pointer type, but you cannot dereference the
result without invoking undefined behaviour. Your code is akin to
calling exit() without including <stdlib.h> in C89: you can't call
a void function as if it were an int function.

It is not possible to call a void function in such a program without
using the comma operator. Fortunately, no C or C++ standard requires
the function main to terminate through an exit call or a return statement.


Yeah. I know. But it works on my system :) And exit never returns, so there
is no reason to worry about the return value (or lack there of). All you
have to worry about is that the next instruction is that start of the exit
function. After that nothing matters.

--
Scott
Nov 14 '05 #197
On Mon, 28 Jun 2004 04:16:52 +0300, Ioannis Vranos wrote:
Given an array (group) of numbers write all the possible sub groups of
this group.

std::next_permutation and std::prev_permutation. An example:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
using namespace std;

string s="abcd";
do
cout<<s<<endl;
while(next_permutation(s.begin(), s.end()));
}


and if
unsigned s={12222, 839939, 9393999, 9099999, 98394763, 89383883};
Next_permutation is ok?
if not for me next_permutation==fuochino, deve essere modificata
esiste una soluzione non ricorsiva
Nov 14 '05 #198
On Thu, 01 Jul 2004 16:14:31 GMT, RoSsIaCrIiLoIA <n@esiste.ee> wrote:
On Mon, 28 Jun 2004 04:16:52 +0300, Ioannis Vranos wrote:
> Given an array (group) of numbers write all the possible sub groups of
> this group.std::next_permutation and std::prev_permutation. An example:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
using namespace std;

string s="abcd";
do
cout<<s<<endl;
while(next_permutation(s.begin(), s.end()));
}


and if
unsigned s={12222, 839939, 9393999, 9099999, 98394763, 89383883};
Next_permutation is ok?

unsigned *s = {12222, 839939, 9393999, 9099999, 98394763, 89383883};
if not for me next_permutation==fuochino, deve essere modificata
esiste una soluzione non ricorsiva


it is wrong excuse me
Nov 14 '05 #199
Da*****@cern.ch (Dan Pop) wrote:
In <jk********************************@4ax.com> Irrwahn Grausewitz <ir*******@freenet.de> writes:
1. Technically, the discussion is about objects, identifiers that ^^^^^^^^^^^ designate/denote objects (aka variable names in C++), and values.
Nope, the discussion was about "variables".


Then, pray tell, how is the term "variable" defined, WRT to the C
language? Those who were using it were actually talking about named
objects, *technically*. However, except for C++, the term variable
isn't officially defined to mean "named object".
As long as c.l.c is still an imperfect ivory tower (i.e. it still has
connections with the real world) it is highly unrealistic to ignore
popular CS jargon terms like "variable" and "global", simply because the
C standard itself doesn't use them.


It's indeed highly unrealistic to expect everyone to avoid those
terms. However, a quick look in the archives shows that the use of
correct, well-defined terms, instead of sloppy jargon, serves well to
reduce the risk of confusion. What's wrong with object, external
linkage, file scope, etc.pp., after all?

Regards
--
Irrwahn Grausewitz (ir*******@freenet.de)
welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
clc OT guide : http://benpfaff.org/writings/clc/off-topic.html
Nov 14 '05 #200

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

Similar topics

270
by: Jatinder | last post by:
I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these...
12
by: G. | last post by:
Hi all, During my degree, BEng (Hons) Electronics and Communications Engineering, we did C programming every year, but I never kept it up, as I had no interest and didn't see the point. But now...
11
by: John Salerno | last post by:
Similar to the Python Challenge, does anyone know of any other websites or books that have programming puzzles to solve? I found a book called "Puzzles for Hackers", but it seems like it might be a...
1
by: xavier vazquez | last post by:
I have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of...
0
by: xavier vazquez | last post by:
have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the...
44
by: Jon Harrop | last post by:
Microsoft Research are developing a functional programming language called F# for .NET and I've been playing with it recently. I've uploaded some demos here: ...
5
by: ashish0799 | last post by:
HI I M ASHISH I WANT ALGORYTHMUS OF THIS PROBLEM Jigsaw puzzles. You would have solved many in your childhood and many people still like it in their old ages also. Now what you have got to do...
3
by: oncue01 | last post by:
Word Puzzle Task You are going to search M words in an N × N puzzle. The words may have been placed in one of the four directions as from (i) left to right (E), (ii) right to left (W), (iii) up...
4
by: honey777 | last post by:
Problem: 15 Puzzle This is a common puzzle with a 4x4 playing space with 15 tiles, numbered 1 through 15. One "spot" is always left blank. Here is an example of the puzzle: The goal is to...
13
by: btkuhn | last post by:
Hi guys, I'm learning Python by teaching myself, and after going through several tutorials I feel like I've learned the basics. Since I'm not taking a class or anything, I've been doing...
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
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,...
0
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...
1
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...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.