pr********@gmail.com wrote:
hii,
plz help to knw how this prg wrk in detail
#define CUBE(x) (x*x*x)
main()
{
int a,b=3;
a=CUBE(b++);
printf("%d%d",a,b);
}
Others have said that this program causes undefined behaviour. What does
this mean? It means Bad Things.
The C programming language is defined by a set of standards published by
ISO. The main ones are C89 (the first one), and C99 (the most recent).
The standard describes what a valid C compiler (or to use the Standard's
language, "implementation") must do. In certain places, the standard
gives the implementation a range of options - e.g. int can be any size,
as long as it's 16 bits or more.
For a program which causes undefined behaviour (UB), the standard places
no restrictions on the implementation. This means that the
implementation can do *anything it likes* when it encounters UB. What
this means is that a compiler which is in every way a working and
correct C compiler can fail to compile your code - or worse, compile
your code into something with bugs in it. Given there are hundreds (if
not thousands) of C implementations out there, this is a Bad Thing.
Of course, you may find that *your* compiler works exactly as you expect
it to. This is allowed by the Standard, because it places no
restrictions on the compiler. But one of the reasons for writing in C is
that there are many different C compilers on many different types of
computer, and if you do not invoke UB then the Standard guarantees your
program will work on *all* of these compilers without needing a rewrite.
This is called "portability". If you rely on quirks of your own
compiler, it may not compile on any other.
Why would you want to write code that will compile on any C compiler?
Well, it might be nice if you could give (or sell!) your nice Windows
program to Linux users at no extra cost to yourself. Another reason is
that if you write C code that works on lots of C compilers, then users
of all those compilers will know what you mean and will be able to help.
If you write C code which only works on your compiler, then you cut
yourself off from that expertise, because users of other compilers are
not familiar with the quirks of your compiler.
There are sometimes good reasons for writing code for which the Standard
does not define correct behaviour. This includes using system-specific
features such as graphics, networks, when standard C code to achieve
what you want doesn't exist. However in this situation standard C code
to do what you want *does* exist, so you should write standard C.
--
Philip Potter pgp <atdoc.ic.ac.uk