By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,037 Members | 2,065 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,037 IT Pros & Developers. It's quick & easy.

Puzzling program

P: n/a
Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.

Thanks for any help.

RD

Aug 8 '07 #1
Share this Question
Share on Google+
73 Replies


P: n/a

"Rajeet Dalawal" <rd@mailinator.comwrote in message
news:sl********************@nospam.invalid...
Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.

Thanks for any help.
The interviewer is looking for you to understand that C data is stored in
memory as bytes, and that by playing about with pointers you can cause the
bits to be reinterpreted as different types.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Aug 8 '07 #2

P: n/a
Rajeet Dalawal wrote:
Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.

Thanks for any help.

RD
Please allow me..

#include <stdio.h>
int main(void) {
char *s = "abc";
int *i = (int *)s;
printf("%08x", *i);
return 0;
}

I'll assume Intel CPU and ASCII characters.
You have s pointing to a four-byte string, in hex, 61 62 63 00.
Intel is little-endian. When you treat those four bytes as an int and
the print it as hex, the result is 00636261.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Aug 8 '07 #3

P: n/a

"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
It's either a very bad interview question or a very good one. 5
points for explaining the behavior; 50 points for finding all the
errors in the code (and -100 points to the interviewer if he thinks
it's a valid program).
You could point out all the errors and nonportable assumptions in the code.
But you are not interviewing the interviewer, probably. He's deciding
whether he wants you, and you would be very uncertain of the reaction you
would get.
Companies want "team players", corporate-speak for the word they dare not
use, obedience.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Aug 8 '07 #4

P: n/a
Rajeet Dalawal said:
Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261?
No, it isn't. The question is: why is the interviewer asking you this
question? Is it to test your understanding that the program is
bug-ridden? The program comprises five lines of code, if we don't count
the braces. I can immediately see three instances of undefined
behaviour and three instances of poor style (not "pretty-pretty" style,
but "let's-prevent-bugs-and-get-the-output-right" style. The bug rate
(errors per line) is simply staggering - possibly even higher than
Schildt's.

Others have pointed out the errors themselves, so I won't repeat them
here.

In your situation, I would explain, not the *output* of the program, but
the *problems* with it. If the interviewer starts nodding
encouragingly, that might indicate that it's a "lamer test", in which
case all might yet be well.

If, on the other hand, he or she looks puzzled or disbelieving as you
explain the problems, thank him or her for the sandwiches and coffee,
make your excuses, and leave. You don't want to work there.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 9 '07 #5

P: n/a
In article <5h*************@mid.individual.net>,
Martin Ambuhl <ma*****@earthlink.netwrote:
>Be glad you don't understand this piece of garbage. Anyone who could
write this crap and expect a known result of compilation, not to mention
execution, is a fool. You don't want to work with such people. They
will create bugs as fast as they code, and you will be assigned to fix them.
I completely disagree. Obviously such code is not portable, and
unlikely to be useful even if the system is known. But knowing the
details of the C standard isn't all there is to being a C programmer,
and someone who has no idea what is going on underneath would not be
my choice. We should encourage the desire to know how things work.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Aug 9 '07 #6

P: n/a
"Malcolm McLean" <re*******@btinternet.comwrites:
"Keith Thompson" <ks***@mib.orgwrote in message
news:ln************@nuthaus.mib.org...
>It's either a very bad interview question or a very good one. 5
points for explaining the behavior; 50 points for finding all the
errors in the code (and -100 points to the interviewer if he thinks
it's a valid program).
You could point out all the errors and nonportable assumptions in the
code. But you are not interviewing the interviewer, probably. He's
deciding whether he wants you, and you would be very uncertain of the
reaction you would get.
Companies want "team players", corporate-speak for the word they dare
not use, obedience.
This has veered off-topic, so I'll just strongly disagree and move on.
If you'd care to redirect this to a more appropriate newsgroup (I'm
not sure which one), I might follow the discussion there.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 9 '07 #7

P: n/a
In article <At*********************@bt.com>,
Richard Heathfield <rj*@see.sig.invalidwrote:
>The question is: why is the output 636261?
>No, it isn't. The question is: why is the interviewer asking you this
question? Is it to test your understanding that the program is
bug-ridden? The program comprises five lines of code, if we don't count
the braces. I can immediately see three instances of undefined
behaviour and three instances of poor style (not "pretty-pretty" style,
but "let's-prevent-bugs-and-get-the-output-right" style. The bug rate
(errors per line) is simply staggering - possibly even higher than
Schildt's.

Others have pointed out the errors themselves, so I won't repeat them
here.

In your situation, I would explain, not the *output* of the program, but
the *problems* with it. If the interviewer starts nodding
encouragingly, that might indicate that it's a "lamer test", in which
case all might yet be well.

If, on the other hand, he or she looks puzzled or disbelieving as you
explain the problems, thank him or her for the sandwiches and coffee,
make your excuses, and leave. You don't want to work there.
While all this is quite reasonable, it's still true that any
experienced C programmer should be able to explain why the output is,
in fact, quite likely to be 636261.

-- Richard

--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Aug 9 '07 #8

P: n/a
Martin Ambuhl <ma*****@earthlink.netwrites:
Rajeet Dalawal wrote:
>Good day group.
I was asked in an interview to explain the behavior of this program.
void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}
The question is: why is the output 636261?

Because:
a) The illiterate return type 'void' for main makes all bets off.
b) The illiterate omission of the required prototype for the variadic
function printf makes all bets off.
c) The illiterate absence of an end-of-line character ending the
last line of output makes all bets off.
Dang, I missed that one!

[other excellent points snipped]
Be glad you don't understand this piece of garbage. Anyone who could
write this crap and expect a known result of compilation, not to
mention execution, is a fool. You don't want to work with such
people. They will create bugs as fast as they code, and you will be
assigned to fix them.
Yes, it's undefined garbage, but I understand what it's *intended* to
do, and I'd actually expect it to yield one of a couple of results on
most systems, though I'd be unsurprised to see something radically
different . (Yeah, I went and tried it before writing that.)

If someone wrote that program *and thought it was valid*, I'd assume
the author was either (a) a newbie who needs to unlearn a few things
before he can move on to write decent code (ignorance is curable) or
(b) incompetent.

*But* any experienced C programmer should, in addition to recognizing
the astonishing number of bugs, be able to explain *why* the program
prints 636261 (and what that says about the implementation). Even
competent programmers make mistakes (though not with the density seen
in this example), and understanding the probable explanation for the
specific behavior of a buggy program is a valuable skill. Certainly
the goal should be to eliminate any undefined behavior (and, if
possible unspecified behavior) and produce a correct program, but
understanding a particular manifestation of UB can be an important
step in achieving that goal.

And, as I speculated elsethread, the errors may actually have been the
point of the interview question.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 9 '07 #9

P: n/a
[snips]

On Thu, 09 Aug 2007 00:26:19 +0100, Malcolm McLean wrote:
You could point out all the errors and nonportable assumptions in the code.
But you are not interviewing the interviewer, probably. He's deciding
whether he wants you, and you would be very uncertain of the reaction you
would get.
Companies want "team players", corporate-speak for the word they dare not
use, obedience.
Perhaps they do, but I've seen questions such as this _precisely_ to
determine whether you're the sort who turns down the warning level and
prays, or if you're the sort who has at least some clue why the code is
wrong.
Aug 9 '07 #10

P: n/a
Richard Tobin said:

<snip>
While all this is quite reasonable, it's still true that any
experienced C programmer should be able to explain why the output is,
in fact, quite likely to be 636261.
But it isn't! On my system, for example, the program prints "a suffusion
of yellow".

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 9 '07 #11

P: n/a
Keith Thompson wrote:
>> printf("%x", *i);

Also, calling printf with no prototype in scope invokes undefined
behavior (the fix is to add a '#include <stdio.h>' to the top of the
source file). And "%x" is the wrong format for printing an int;
probably 'i' should have been declared as an unsigned int* (the
standard *almost* says that it will work anyway, but it's not
something I'd be comfortable counting on).
also, no newline and the end of the program is reached...
Aug 9 '07 #12

P: n/a
>>>>"RH" == Richard Heathfield <rj*@see.sig.invalidwrites:

RHRichard Tobin said: <snip>
>While all this is quite reasonable, it's still true that any
experienced C programmer should be able to explain why the
output is, in fact, quite likely to be 636261.
RHBut it isn't! On my system, for example, the program prints "a
RHsuffusion of yellow".

Fortunately, you have a DeathStation 2000. I ran it on my
DeathStation 3000, and I'm hoping my eyebrows grow back.

Charlton
--
Charlton Wilbur
cw*****@chromatico.net
Aug 9 '07 #13

P: n/a
>>>>"MMcL" == Malcolm McLean <re*******@btinternet.comwrites:

MMcLYou could point out all the errors and nonportable
MMcLassumptions in the code. But you are not interviewing the
MMcLinterviewer, probably. He's deciding whether he wants you,
MMcLand you would be very uncertain of the reaction you would
MMcLget.

If the interviewer quizzes you on bad code and expects you to toe the
line rather than fix things, that's a strong clue about the corporate
culture that a competent and professional programmer ignores at his or
her peril. And while the interviewer is deciding whether or not he
wants to hire the candidate, the candidate is deciding whether or not
he wants to work for that company.

I've been on more than one interview where it was clear by the end of
the interview that this was *not* a company I had any interest in
working for, for issues of culture and group competence.

Charlton
--
Charlton Wilbur
cw*****@chromatico.net
Aug 9 '07 #14

P: n/a
On Wed, 08 Aug 2007 19:36:27 -0400, Martin Ambuhl
<ma*****@earthlink.netwrote:
>Rajeet Dalawal wrote:
>Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261?

Because:
a) The illiterate return type 'void' for main makes all bets off.
b) The illiterate omission of the required prototype for the variadic
function printf makes all bets off.
c) The illiterate absence of an end-of-line character ending the
last line of output makes all bets off.
What do you mean by "all bets off"? Do you mean undefined behavior? I
don't think it is undefined behavior.

Consider:

#include <stdio.h>
int main(void)
{
printf("Hello world!");
return 0;
}

There is no end-of-line character ending the last line of output. Yet,
as far as the C standard is concerned, this is well-defined behavior.
The definition of the word "flushed" is found in Section 7.19.3.(4):

"A file may be disassociated from a controlling stream by closing the
file. Output streams are flushed (any unwritten buffer contents are
transmitted to the host environment) before the stream is
disassociated from the file."

Then, from Section 7.19.3.(5):

"The file may be subsequently reopened, by the same or another program
execution, and its contents reclaimed or modified (if it can be
repositioned at its start). If the main function returns to its
original caller, or if the exit function is called, all open files are
closed (hence all output streams are flushed) before program
termination."

From these two sections, we know that, before program termination, the
following statement:

printf("Hello world!");

results in any unwritten buffer contents being transmitted to the host
environment.

What the host environment does with a final buffer that does not
contain an "end-of-line" character is completely beyond the
jurisdiction of the C standard, and thusly there is no possibility of
undefined behavior.

Admittedly, it is not a good idea to omit an end-of-line character
ending the last line of output. That's because what you expect to be
output may not be output, and it all depends on the host environment
as to whether or not the program output behaves as expected. Again,
this is not undefined behavior, as far as the C standard is concerned.

Regards
--
jay
Aug 9 '07 #15

P: n/a
On Wed, 08 Aug 2007 19:36:27 -0400, Martin Ambuhl
<ma*****@earthlink.netwrote:
>Rajeet Dalawal wrote:
>Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261?

Because:
a) The illiterate return type 'void' for main makes all bets off.
b) The illiterate omission of the required prototype for the variadic
function printf makes all bets off.
c) The illiterate absence of an end-of-line character ending the
last line of output makes all bets off.
What do you mean by "all bets off"? Do you mean undefined behavior? I
don't think it is undefined behavior.

Consider:

#include <stdio.h>
int main(void)
{
printf("Hello world!");
return 0;
}

There is no end-of-line character ending the last line of output. Yet,
as far as the C standard is concerned, this is well-defined behavior.
The definition of the word "flushed" is found in Section 7.19.3.(4):

"A file may be disassociated from a controlling stream by closing the
file. Output streams are flushed (any unwritten buffer contents are
transmitted to the host environment) before the stream is
disassociated from the file."

Then, from Section 7.19.3.(5):

"The file may be subsequently reopened, by the same or another program
execution, and its contents reclaimed or modified (if it can be
repositioned at its start). If the main function returns to its
original caller, or if the exit function is called, all open files are
closed (hence all output streams are flushed) before program
termination."

From these two sections, we know that, before program termination, the
following statement:

printf("Hello world!");

results in any unwritten buffer contents being transmitted to the host
environment.

What the host environment does with a final buffer that does not
contain an "end-of-line" character is completely beyond the
jurisdiction of the C standard, and thusly there is no possibility of
undefined behavior.

Admittedly, it is not a good idea to omit an end-of-line character
ending the last line of output. That's because what you expect to be
output may not be output, and it all depends on the host environment
as to whether or not the program output behaves as expected. Again,
this is not undefined behavior, as far as the C standard is concerned.

Regards
--
jay
Aug 9 '07 #16

P: n/a
On Wed, 08 Aug 2007 19:36:27 -0400, Martin Ambuhl
<ma*****@earthlink.netwrote:
>Rajeet Dalawal wrote:
>Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261?

Because:
a) The illiterate return type 'void' for main makes all bets off.
b) The illiterate omission of the required prototype for the variadic
function printf makes all bets off.
c) The illiterate absence of an end-of-line character ending the
last line of output makes all bets off.
What do you mean by "all bets off"? Do you mean undefined behavior? I
don't think it is undefined behavior.

Consider:

#include <stdio.h>
int main(void)
{
printf("Hello world!");
return 0;
}

There is no end-of-line character ending the last line of output. Yet,
as far as the C standard is concerned, this is well-defined behavior.
The definition of the word "flushed" is found in Section 7.19.3.(4):

"A file may be disassociated from a controlling stream by closing the
file. Output streams are flushed (any unwritten buffer contents are
transmitted to the host environment) before the stream is
disassociated from the file."

Then, from Section 7.19.3.(5):

"The file may be subsequently reopened, by the same or another program
execution, and its contents reclaimed or modified (if it can be
repositioned at its start). If the main function returns to its
original caller, or if the exit function is called, all open files are
closed (hence all output streams are flushed) before program
termination."

From these two sections, we know that, before program termination, the
following statement:

printf("Hello world!");

results in any unwritten buffer contents being transmitted to the host
environment.

What the host environment does with a final buffer that does not
contain an "end-of-line" character is completely beyond the
jurisdiction of the C standard, and thusly there is no possibility of
undefined behavior.

Admittedly, it is not a good idea to omit an end-of-line character
ending the last line of output. That's because what you expect to be
output may not be output, and it all depends on the host environment
as to whether or not the program output behaves as expected. Again,
this is not undefined behavior, as far as the C standard is concerned.

Regards
--
jay
Aug 9 '07 #17

P: n/a
On Wed, 08 Aug 2007 19:36:27 -0400, Martin Ambuhl
<ma*****@earthlink.netwrote:
>Rajeet Dalawal wrote:
>Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261?

Because:
a) The illiterate return type 'void' for main makes all bets off.
b) The illiterate omission of the required prototype for the variadic
function printf makes all bets off.
c) The illiterate absence of an end-of-line character ending the
last line of output makes all bets off.
What do you mean by "all bets off"? Do you mean undefined behavior? I
don't think it is undefined behavior.

Consider:

#include <stdio.h>
int main(void)
{
printf("Hello world!");
return 0;
}

There is no end-of-line character ending the last line of output. Yet,
as far as the C standard is concerned, this is well-defined behavior.
The definition of the word "flushed" is found in Section 7.19.3.(4):

"A file may be disassociated from a controlling stream by closing the
file. Output streams are flushed (any unwritten buffer contents are
transmitted to the host environment) before the stream is
disassociated from the file."

Then, from Section 7.19.3.(5):

"The file may be subsequently reopened, by the same or another program
execution, and its contents reclaimed or modified (if it can be
repositioned at its start). If the main function returns to its
original caller, or if the exit function is called, all open files are
closed (hence all output streams are flushed) before program
termination."

From these two sections, we know that, before program termination, the
following statement:

printf("Hello world!");

results in any unwritten buffer contents being transmitted to the host
environment.

What the host environment does with a final buffer that does not
contain an "end-of-line" character is completely beyond the
jurisdiction of the C standard, and thusly there is no possibility of
undefined behavior.

Admittedly, it is not a good idea to omit an end-of-line character
ending the last line of output. That's because what you expect to be
output may not be output, and it all depends on the host environment
as to whether or not the program output behaves as expected. Again,
this is not undefined behavior, as far as the C standard is concerned.

Regards
--
jay
Aug 9 '07 #18

P: n/a
On Wed, 08 Aug 2007 19:36:27 -0400, Martin Ambuhl
<ma*****@earthlink.netwrote:
>Rajeet Dalawal wrote:
>Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261?

Because:
a) The illiterate return type 'void' for main makes all bets off.
b) The illiterate omission of the required prototype for the variadic
function printf makes all bets off.
c) The illiterate absence of an end-of-line character ending the
last line of output makes all bets off.
What do you mean by "all bets off"? Do you mean undefined behavior? I
don't think it is undefined behavior.

Consider:

#include <stdio.h>
int main(void)
{
printf("Hello world!");
return 0;
}

There is no end-of-line character ending the last line of output. Yet,
as far as the C standard is concerned, this is well-defined behavior.
The definition of the word "flushed" is found in Section 7.19.3.(4):

"A file may be disassociated from a controlling stream by closing the
file. Output streams are flushed (any unwritten buffer contents are
transmitted to the host environment) before the stream is
disassociated from the file."

Then, from Section 7.19.3.(5):

"The file may be subsequently reopened, by the same or another program
execution, and its contents reclaimed or modified (if it can be
repositioned at its start). If the main function returns to its
original caller, or if the exit function is called, all open files are
closed (hence all output streams are flushed) before program
termination."

From these two sections, we know that, before program termination, the
following statement:

printf("Hello world!");

results in any unwritten buffer contents being transmitted to the host
environment.

What the host environment does with a final buffer that does not
contain an "end-of-line" character is completely beyond the
jurisdiction of the C standard, and thusly there is no possibility of
undefined behavior.

Admittedly, it is not a good idea to omit an end-of-line character
ending the last line of output. That's because what you expect to be
output may not be output, and it all depends on the host environment
as to whether or not the program output behaves as expected. Again,
this is not undefined behavior, as far as the C standard is concerned.

Regards
--
jay
Aug 9 '07 #19

P: n/a
ri*****@cogsci.ed.ac.uk (Richard Tobin) wrote:
Richard Heathfield <rj*@see.sig.invalidwrote:
In your situation, I would explain, not the *output* of the program, but
the *problems* with it. If the interviewer starts nodding
encouragingly, that might indicate that it's a "lamer test", in which
case all might yet be well.

If, on the other hand, he or she looks puzzled or disbelieving as you
explain the problems, thank him or her for the sandwiches and coffee,
make your excuses, and leave. You don't want to work there.

While all this is quite reasonable, it's still true that any
experienced C programmer should be able to explain why the output is,
in fact, quite likely to be 636261.
Should be able to, yes. Should be willing to without first explaining
why this output is only likely on modern desktop systems, and why it is
a bad idea to write code like that, no.

Richard
Aug 9 '07 #20

P: n/a
Lew Pitcher wrote:
Rajeet Dalawal wrote:
>Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.

The answer is that the program is poorly written and invokes behaviour that is
not defined by the C standard. As "undefined behaviour" means that anything
can happen, the output value of 636\261 is just as valid (and just as likely)
as any other output.
This is not true, and it doesn't help explain the danger of undefined
behaviour. Indeed, one of the problems of undefined behaviour is that it
may well compile and do what you expect, and in some cases is very
likely to do so. But because the behaviour is undefined, there are no
guarantees that porting to a different system, or even just getting a
new version of the same compiler, won't break your program.

Phil
Aug 9 '07 #21

P: n/a
On Aug 9, 12:31 am, Rajeet Dalawal <r...@mailinator.comwrote:
Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);

}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.

Thanks for any help.

RD
I'd never like to work for a company where interviewers declare main
as a void function...

Aug 9 '07 #22

P: n/a
On Wed, 08 Aug 2007 16:18:04 -0700, Keith Thompson wrote:
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
>In article <sl********************@nospam.invalid>,
Rajeet Dalawal <rd@mailinator.comwrote:
>>>Good day group.
>>>I was asked in an interview to explain the behavior of this program.
>>>void main()

void main() is undefined behaviour on a hosted system.
>>>{
char *s = "abc";
int *i = (int *) s;

Style point: 'i' is a lousy name for a pointer.
>Undefined behaviour. The string "abc" might not be suitably
aligned for use as an integer.
>> printf("%x", *i);

Also, calling printf with no prototype in scope invokes undefined
behavior (the fix is to add a '#include <stdio.h>' to the top of the
source file). And "%x" is the wrong format for printing an int;
probably 'i' should have been declared as an unsigned int* (the
standard *almost* says that it will work anyway, but it's not
something I'd be comfortable counting on).
For sufficiently large values of "almost". See 6.5.2.2p6, the part
with in n1124.pdf is on the beginning of the next page.
Also see the first sentence of 6.2.5p9.
You were thinking about the fact that *i could be negative?
--
Army1987 (Replace "NOSPAM" with "email")
No-one ever won a game by resigning. -- S. Tartakower

Aug 9 '07 #23

P: n/a
In article <11**********************@m37g2000prh.googlegroups .com>,
Jalapeno <ja*******@mac.comwrote:
>The question is: why is the output 636261?
>When I run your program I get the following output:

81828300
"Why is the output 636261" doesn't mean "why is everyone's output 636261".
Its natural interpretation in context is "if the output is 636261, what
can you tell me about the C implementation". Good answers include "you're
not using z/OS".

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Aug 9 '07 #24

P: n/a
Army1987 <ar******@NOSPAM.itwrites:
On Wed, 08 Aug 2007 16:18:04 -0700, Keith Thompson wrote:
[...]
>Also, calling printf with no prototype in scope invokes undefined
behavior (the fix is to add a '#include <stdio.h>' to the top of the
source file). And "%x" is the wrong format for printing an int;
probably 'i' should have been declared as an unsigned int* (the
standard *almost* says that it will work anyway, but it's not
something I'd be comfortable counting on).
For sufficiently large values of "almost". See 6.5.2.2p6, the part
with in n1124.pdf is on the beginning of the next page.
Also see the first sentence of 6.2.5p9.
You were thinking about the fact that *i could be negative?
6.2.5p9 is what I was thinking of (though I hadn't bothered to look it
up). It guarantees the same representation, but the statement that

The same representation and alignment requirements are meant to
imply interchangeability as arguments to functions, return values
from functions, and members of unions.

is relegated to a footnote; thus my use of the word "almost". I
hadn't been aware of 6.5.2.2p6, which makes the guarantee explicitly
in normative text.

But after re-reading 6.5.2.2p6 a couple of times, I don't think it
actually applies here. That paragraph talks about calling a function
with no visible prototype. If the function is *not* variadic, you can
pass a signed int argument for an unsigned int parameter (or vice
versa) as long as the value is representable in both types. But the
example involves a call to printf(), which is variadic. Calling a
variadic function with no prototype is undefined behavior regardless
of the arguments; even 'printf("hello")' invokes UB if there's no
prototype.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 9 '07 #25

P: n/a
On Thu, 09 Aug 2007 10:11:36 -0700, Keith Thompson wrote:
Army1987 <ar******@NOSPAM.itwrites:
>On Wed, 08 Aug 2007 16:18:04 -0700, Keith Thompson wrote:
[...]
>>Also, calling printf with no prototype in scope invokes undefined
behavior (the fix is to add a '#include <stdio.h>' to the top of the
source file). And "%x" is the wrong format for printing an int;
probably 'i' should have been declared as an unsigned int* (the
standard *almost* says that it will work anyway, but it's not
something I'd be comfortable counting on).
For sufficiently large values of "almost". See 6.5.2.2p6, the part
with in n1124.pdf is on the beginning of the next page.
Also see the first sentence of 6.2.5p9.
You were thinking about the fact that *i could be negative?

6.2.5p9 is what I was thinking of (though I hadn't bothered to look it
up). It guarantees the same representation, but the statement that

The same representation and alignment requirements are meant to
imply interchangeability as arguments to functions, return values
from functions, and members of unions.

is relegated to a footnote; thus my use of the word "almost". I
hadn't been aware of 6.5.2.2p6, which makes the guarantee explicitly
in normative text.

But after re-reading 6.5.2.2p6 a couple of times, I don't think it
actually applies here. That paragraph talks about calling a function
with no visible prototype. If the function is *not* variadic, you can
pass a signed int argument for an unsigned int parameter (or vice
versa) as long as the value is representable in both types. But the
example involves a call to printf(), which is variadic. Calling a
variadic function with no prototype is undefined behavior regardless
of the arguments; even 'printf("hello")' invokes UB if there's no
prototype.
Right, I had misread it. (The standard also makes the guarantee
referring to va_arg, but doesn't require printf to be implemented
using it.)
--
Army1987 (Replace "NOSPAM" with "email")
No-one ever won a game by resigning. -- S. Tartakower

Aug 9 '07 #26

P: n/a
jt@toerring.de (Jens Thoms Toerring) writes:
[...]
But that's not all: you need another
stroke of luck to get this program to work since there are a lot
of machines where an int can't start at arbitrary addresses but
only e.g. at even addresses (or addreses that can be divided by
4 etc.), while a char can always reside at all addresses. If on
such a machine the string does not start at an address where also
an int can start (and there's no way you can make sure of this)
then the program probably will crash with an SIGBUS error when
'i' gets dereferenced.
For context, here are the relevant lines from the original cruddy
program:

char *s = "abc";
int *i = (int *) s;

It's certainly true that there's no guarantee that the string has any
particular alignment, but I think most implementations do tend to
store strings (and, more generally, arrays) at a stricter alignment
than is required. Doing so can have some performance advantages. For
example, an implementation of memcpy(), or even strcpy(), might use
word moves whenever both the source and the target are suitably
aligned.

It's yet another instance of undefined behavior that's very likely to
work as expected (unfortunately).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 9 '07 #27

P: n/a
Keith Thompson <ks***@mib.orgwrote:
jt@toerring.de (Jens Thoms Toerring) writes:
[...]
But that's not all: you need another
stroke of luck to get this program to work since there are a lot
of machines where an int can't start at arbitrary addresses but
only e.g. at even addresses (or addreses that can be divided by
4 etc.), while a char can always reside at all addresses. If on
such a machine the string does not start at an address where also
an int can start (and there's no way you can make sure of this)
then the program probably will crash with an SIGBUS error when
'i' gets dereferenced.
For context, here are the relevant lines from the original cruddy
program:
char *s = "abc";
int *i = (int *) s;
It's certainly true that there's no guarantee that the string has any
particular alignment, but I think most implementations do tend to
store strings (and, more generally, arrays) at a stricter alignment
than is required. Doing so can have some performance advantages. For
example, an implementation of memcpy(), or even strcpy(), might use
word moves whenever both the source and the target are suitably
aligned.

It's yet another instance of undefined behavior that's very likely to
work as expected (unfortunately).
Well, we can modify it a bit to increase the odds of it failing on a
machine with stricter alignment requirements;-) One way would be

char *s = "Aabc";
int *i = (int *) (s + 1);
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Aug 9 '07 #28

P: n/a

"Charlton Wilbur" <cw*****@chromatico.netwrote in message
news:87************@mithril.chromatico.net...
And while the interviewer is deciding whether or not he
wants to hire the candidate, the candidate is deciding whether or not
he wants to work for that company.
Sometimes you are in that fortunate position. But it is still better to get
the offer and turn them down at that stage.
For a lot of people professional fulfillment is low down the list. For
instance for personal reasons my last job had to be in Leeds. There were
exactly three games companies in the city. So I was glad to be offered a job
on my first interview, despite not really liking sports games. Otherwise I
would have been running out of options quite quickly.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Aug 9 '07 #29

P: n/a
Army1987 <ar******@NOSPAM.itwrites:
On Thu, 09 Aug 2007 10:11:36 -0700, Keith Thompson wrote:
[...]
>But after re-reading 6.5.2.2p6 a couple of times, I don't think it
actually applies here. That paragraph talks about calling a function
with no visible prototype. If the function is *not* variadic, you can
pass a signed int argument for an unsigned int parameter (or vice
versa) as long as the value is representable in both types. But the
example involves a call to printf(), which is variadic. Calling a
variadic function with no prototype is undefined behavior regardless
of the arguments; even 'printf("hello")' invokes UB if there's no
prototype.
Right, I had misread it. (The standard also makes the guarantee
referring to va_arg, but doesn't require printf to be implemented
using it.)
Right (C99 7.15.1.1p2), but that guarantee doesn't apply if the
function is called without a visible prototype.

Calling a variadic function with no visible prototype is undefined
behavior, regardless of the arguments.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 9 '07 #30

P: n/a
Steffen Buehler <st*************@mailinator.comwrote:
When you want to know to what value a pointer is pointing, the program
in your example takes *four* bytes starting at the address where "abc"
Not quite right; it takes sizeof(int) bytes, which on OP's machine
(and the interviewer's machine) is 4.

--
C. Benson Manica | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
sdf.lonestar.org | Google groups, due to rampant unchecked spam.
Aug 9 '07 #31

P: n/a
Rajeet Dalawal <rd@mailinator.comwrote:
Here's what I'd expect to happen: s is a pointer to an array of chars,
but the char it actually points to is 'a'. This has value 0x61. So when
this gets typecast to an integer, the standard promotion char -int
should mean that *i takes the value 0x61 as well.
This program does what you just described:

#include <stdio.h>

int main(void)
{
char *s = "abc";
int i = *s;
printf("%08x\n", i);
return 0;
}

Note the differences between this and the original program.

--
C. Benson Manica | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
sdf.lonestar.org | Google groups, due to rampant unchecked spam.
Aug 9 '07 #32

P: n/a
Joe Wright <jo********@comcast.netwrote:
Please allow me..
Likewise...
#include <stdio.h>
int main(void) {
char *s = "abc";
int *i = (int *)s;
printf("%08x", *i);
printf("%08x\n", *i);
return 0;
}
--
C. Benson Manica | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
sdf.lonestar.org | Google groups, due to rampant unchecked spam.
Aug 9 '07 #33

P: n/a
Lew Pitcher <lp******@teksavvy.comwrote:
The answer is that the program is poorly written and invokes behaviour that is
not defined by the C standard. As "undefined behaviour" means that anything
can happen, the output value of 636\261 is just as valid (and just as likely)
as any other output.
Equally valid, yes, but hardly as likely, unless there are an infinite
number of DS9K implementations to smooth out the spike at 636261
produced by non-evil little endian ASCII implementations.

--
C. Benson Manica | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
sdf.lonestar.org | Google groups, due to rampant unchecked spam.
Aug 9 '07 #34

P: n/a
Christopher Benson-Manica <at***@vinland.freeshell.orgwrites:
Lew Pitcher <lp******@teksavvy.comwrote:
>The answer is that the program is poorly written and invokes
behaviour that is not defined by the C standard. As "undefined
behaviour" means that anything can happen, the output value of
636\261 is just as valid (and just as likely) as any other output.

Equally valid, yes, but hardly as likely, unless there are an infinite
number of DS9K implementations to smooth out the spike at 636261
produced by non-evil little endian ASCII implementations.
But there are an infinite number of DS9K implementations. (They're
not required to exist physically, are they?)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 9 '07 #35

P: n/a
In article <f9**********@chessie.cirr.com>,
Christopher Benson-Manica <at***@vinland.freeshell.orgwrote:
>Equally valid, yes, but hardly as likely, unless there are an infinite
number of DS9K implementations to smooth out the spike at 636261
produced by non-evil little endian ASCII implementations.
It's not the number of implementations that counts. It's the enormous
silent majority of DS9K users.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Aug 9 '07 #36

P: n/a
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.orgwrote:
>But there are an infinite number of DS9K implementations. (They're
not required to exist physically, are they?)
I don't know about infinite, but I've never seen a DS9K that didn't
have at least a dozen different C compilers installed.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Aug 9 '07 #37

P: n/a
On Thu, 9 Aug 2007 00:26:19 +0100, in comp.lang.c , "Malcolm McLean"
<re*******@btinternet.comwrote:
>You could point out all the errors and nonportable assumptions in the code.
But you are not interviewing the interviewer, probably.
Euh, interviews are two-way. Do you really want to work for a company
which employs people who don't care about code errors?
>He's deciding whether he wants you,
And you him.
>Companies want "team players",
They also typically want competent people.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Aug 9 '07 #38

P: n/a
Keith Thompson wrote:
>
Army1987 <ar******@NOSPAM.itwrites:
On Wed, 08 Aug 2007 16:18:04 -0700, Keith Thompson wrote:
[...]
Also, calling printf with no prototype in scope invokes undefined
behavior (the fix is to add a '#include <stdio.h>' to the top of the
source file). And "%x" is the wrong format for printing an int;
probably 'i' should have been declared as an unsigned int* (the
standard *almost* says that it will work anyway, but it's not
something I'd be comfortable counting on).
For sufficiently large values of "almost". See 6.5.2.2p6, the part
with in n1124.pdf is on the beginning of the next page.
Also see the first sentence of 6.2.5p9.
You were thinking about the fact that *i could be negative?

6.2.5p9 is what I was thinking of (though I hadn't bothered to look it
up). It guarantees the same representation, but the statement that

The same representation and alignment requirements are meant to
imply interchangeability as arguments to functions, return values
from functions, and members of unions.

is relegated to a footnote; thus my use of the word "almost". I
hadn't been aware of 6.5.2.2p6, which makes the guarantee explicitly
in normative text.
The wording of the footnote is wishywashy.
Would the footnote mean something different
if it was written this way?:

The same representation and alignment requirements
imply interchangeability as arguments to functions, return values
from functions, and members of unions.
But after re-reading 6.5.2.2p6 a couple of times, I don't think it
actually applies here.
--
pete
Aug 10 '07 #39

P: n/a
Keith Thompson wrote:
>
jt@toerring.de (Jens Thoms Toerring) writes:
[...]
But that's not all: you need another
stroke of luck to get this program to work since there are a lot
of machines where an int can't start at arbitrary addresses but
only e.g. at even addresses (or addreses that can be divided by
4 etc.), while a char can always reside at all addresses. If on
such a machine the string does not start at an address where also
an int can start (and there's no way you can make sure of this)
then the program probably will crash with an SIGBUS error when
'i' gets dereferenced.

For context, here are the relevant lines from the original cruddy
program:

char *s = "abc";
int *i = (int *) s;

It's certainly true that there's no guarantee that the string has any
particular alignment, but I think most implementations do tend to
store strings (and, more generally, arrays) at a stricter alignment
than is required. Doing so can have some performance advantages. For
example, an implementation of memcpy(), or even strcpy(), might use
word moves whenever both the source and the target are suitably
aligned.

It's yet another instance of undefined behavior that's very likely to
work as expected (unfortunately).
There's also a problem when it comes time to read *i,
if sizeof(*i) is greater than sizeof"abc".

--
pete
Aug 10 '07 #40

P: n/a
pete <pf*****@mindspring.comwrites:
Keith Thompson wrote:
>Army1987 <ar******@NOSPAM.itwrites:
On Wed, 08 Aug 2007 16:18:04 -0700, Keith Thompson wrote:
[...]
>Also, calling printf with no prototype in scope invokes undefined
behavior (the fix is to add a '#include <stdio.h>' to the top of the
source file). And "%x" is the wrong format for printing an int;
probably 'i' should have been declared as an unsigned int* (the
standard *almost* says that it will work anyway, but it's not
something I'd be comfortable counting on).
For sufficiently large values of "almost". See 6.5.2.2p6, the part
with in n1124.pdf is on the beginning of the next page.
Also see the first sentence of 6.2.5p9.
You were thinking about the fact that *i could be negative?

6.2.5p9 is what I was thinking of (though I hadn't bothered to look it
up). It guarantees the same representation, but the statement that

The same representation and alignment requirements are meant to
imply interchangeability as arguments to functions, return values
from functions, and members of unions.

is relegated to a footnote; thus my use of the word "almost". I
hadn't been aware of 6.5.2.2p6, which makes the guarantee explicitly
in normative text.

The wording of the footnote is wishywashy.
Would the footnote mean something different
if it was written this way?:

The same representation and alignment requirements
imply interchangeability as arguments to functions, return values
from functions, and members of unions.
[...]

I'm not sure. Since it's a footnote, it's non-normative, so there's
not a whole lot of difference between "are meant to imply" and
"imply". On the other hand, I suppose a less ambiguous statement
would imply that the footnote is merely clarifying something that's
actually stated in normative text; the "are meant to" wording seems to
acknowledge that the normative text doesn't really make this claim.

A hypothetical implementation in which signed int and unsigned int
have exactly the same "representation and alignment requirements", but
are passed as arguments in different registers, would violate the
footnote but not, as far as I can tell, any normative requirement.

If the standard really intended to *require* interchangeability, it
should have said so in normative text. Since it doesn't, my guess is
that the intent is to allow the types *not* to be interchangeable in
some exotic implemntation, but to suggest that they should be if
possible. (But even if my interpretation is correct, I'd be happier
if the standard were more explicit about it.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 10 '07 #41

P: n/a
>>>>"MMcI" == Mark McIntyre <ma**********@spamcop.netwrites:

MMcIOn Thu, 9 Aug 2007 00:26:19 +0100, in comp.lang.c , "Malcolm
MMcIMcLean"
MMcI<re*******@btinternet.comwrote:
>You could point out all the errors and nonportable assumptions
in the code. But you are not interviewing the interviewer,
probably.
MMcIEuh, interviews are two-way. Do you really want to work for
MMcIa company which employs people who don't care about code
MMcIerrors?

Given the quality of the code in his book, do you really want an
answer to that question?

Charlton
--
Charlton Wilbur
cw*****@chromatico.net
Aug 10 '07 #42

P: n/a
Keith Thompson <ks***@mib.orgwrote:
But there are an infinite number of DS9K implementations. (They're
not required to exist physically, are they?)
Now that I think about it, they DO exist physically,

http://en.wikipedia.org/wiki/Many-worlds_interpretation

, although it would not surprise me to learn that those fiendish DS9K
engineers have implemented noncorporeal existence as well.

--
C. Benson Manica | I appreciate all corrections, polite or otherwise.
cbmanica(at)gmail.com |
----------------------| I do not currently read any posts posted through
sdf.lonestar.org | Google groups, due to rampant unchecked spam.
Aug 10 '07 #43

P: n/a
Rajeet Dalawal wrote:
>
Good day group.

I was asked in an interview to explain the behavior of this program.

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.
Short answer:

UB can do *anything*.

Answer the interviewer was probably looking for:

The implementation uses 32-bit integers, is little-endian, and
uses the ASCII character set.

Consider:

What are the raw bytes that s points to?

"abc" --0x61 0x62 0x63 0x00

Given the above criteria (little-endian, 32-bit ints), what
would be the value of *i?

0x00636261

Howver, the output could be different if:

The implementation is not ASCII.

sizeof int != 4

CHAR_BITS != 8

The system is not little-endian.

s is not properly aligned for an int.

The bit-pattern at *i happens to be a trap representation.

The system does not support the non-standard "void main()".

The system treats varadic functions differently, and doesn't
properly compile your printf() call without a prototype in
scope.

The program's output is discarded because it didn't end in '\n'.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>
Aug 10 '07 #44

P: n/a
Mark McIntyre wrote:
>
On Thu, 9 Aug 2007 00:26:19 +0100, in comp.lang.c , "Malcolm McLean"
<re*******@btinternet.comwrote:
You could point out all the errors and nonportable assumptions in the code.
But you are not interviewing the interviewer, probably.

Euh, interviews are two-way. Do you really want to work for a company
which employs people who don't care about code errors?
Well, this may be more a case of "we're only coding for one specific
platform, and don't care about portability". (Not that that's
necessarily a good thing, but at least the code becomes "system
specific behavior" rather than "errors". Of course, what happens
when they decided to port to a similar, but 64-bit, platform?)

[...]

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>
Aug 10 '07 #45

P: n/a
Kenneth Brody <ke******@spamcop.netwrites:
Mark McIntyre wrote:
>On Thu, 9 Aug 2007 00:26:19 +0100, in comp.lang.c , "Malcolm McLean"
<re*******@btinternet.comwrote:
>You could point out all the errors and nonportable assumptions in the code.
But you are not interviewing the interviewer, probably.

Euh, interviews are two-way. Do you really want to work for a company
which employs people who don't care about code errors?

Well, this may be more a case of "we're only coding for one specific
platform, and don't care about portability". (Not that that's
necessarily a good thing, but at least the code becomes "system
specific behavior" rather than "errors". Of course, what happens
when they decided to port to a similar, but 64-bit, platform?)
Here's the original program:

void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}
That's not just system-specific, it's *bad*. Even if you're assuming
a particular set of characteristics for the platform, I can think
of at least four corrections that should be made (add '#include
<stdio.h>', use 'int main(void)', use unsigned int rather than int,
and add a 'return 0;') Not caring about portability is no excuse
for these errors.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 10 '07 #46

P: n/a
>>>>"KB" == Kenneth Brody <ke******@spamcop.netwrites:

KBWell, this may be more a case of "we're only coding for one
KBspecific platform, and don't care about portability". (Not
KBthat that's necessarily a good thing, but at least the code
KBbecomes "system specific behavior" rather than "errors". Of
KBcourse, what happens when they decided to port to a similar,
KBbut 64-bit, platform?)

There are many valid reasons to write nonportable code, but by far the
most common reason I've seen, and it's *not* a valid reason, is
complete ignorance.

If the company doesn't even realize they're writing nonportable code,
it's not a company I want to work for.

Charlton
--
Charlton Wilbur
cw*****@chromatico.net
Aug 10 '07 #47

P: n/a
In article <46***************@spamcop.net>,
Kenneth Brody <ke******@spamcop.netwrote:
>Rajeet Dalawal wrote:
>void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.
>Answer the interviewer was probably looking for:

The implementation uses 32-bit integers, is little-endian, and
uses the ASCII character set.
How optimistic of you. The answer they were looking for could have been:

Integers are laid out in memory with the least significant byte first.

In other words, not just "this code is running on a little-endian platform"
but "the whole world is little-endian, there is no such thing as big-endian,
and no need for us to use or understand the descriptive term little-endian
because there's no alternative from which it needs to be distinguished"

--
Alan Curry
pa****@world.std.com
Aug 10 '07 #48

P: n/a
pa****@TheWorld.com (Alan Curry) writes:
In article <46***************@spamcop.net>,
Kenneth Brody <ke******@spamcop.netwrote:
>>Rajeet Dalawal wrote:
>>void main()
{
char *s = "abc";
int *i = (int *) s;
printf("%x", *i);
}

The question is: why is the output 636261? I don't think I know enough
about C to understand how the conversions between pointer types are
occurring.
>>Answer the interviewer was probably looking for:

The implementation uses 32-bit integers, is little-endian, and
uses the ASCII character set.

How optimistic of you. The answer they were looking for could have been:

Integers are laid out in memory with the least significant byte first.

In other words, not just "this code is running on a little-endian
platform" but "the whole world is little-endian, there is no such
thing as big-endian, and no need for us to use or understand the
descriptive term little-endian because there's no alternative from
which it needs to be distinguished"
Maybe so. If that's really their position, I don't want to work for
them. But if they seem willing to listen when I explain the facts, I
might conclude "Hey, these guys really need me!".

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 10 '07 #49

P: n/a
On Aug 10, 8:11 pm, Keith Thompson <ks...@mib.orgwrote:
use unsigned int rather than int,
I believe it's undefined behavior to cast a char * to an unsigned *
and then dereference it, no less than casting to an int * and then
dereferencing.
and add a 'return 0;') Not caring about portability is no excuse
for these errors.

--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"

Aug 10 '07 #50

73 Replies

This discussion thread is closed

Replies have been disabled for this discussion.