public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* C-Query
@ 2004-09-15  4:23 Shashidhara S Bapat
  2004-09-15  4:39 ` C-Query Sriharsha Vedurmudi
  0 siblings, 1 reply; 2+ messages in thread
From: Shashidhara S Bapat @ 2004-09-15  4:23 UTC (permalink / raw)
  To: gcc-help, Shashidhara Bapat

 Hi All,
I have doubts in the following C program:  (I used gcc compiler)

 >>>
#include <stdio.h>

int main()
{
  int i, j,  b;

  i = 12, j = 1;
  b = ++i + ++i + i++;
  printf("%d\n", b);

  i = 12, j = 1;
  b = j++ + ++j;
  printf("%d\n", b);

  i = 12, j = 1;
  b = ++i + ++i + i++ + j++ + ++j ;
  printf("%d\n", b);

  return 0;
}

and the output of the code is :
42
4
45.

..and my question is why do we get 42 in the first printf? (I was 
expecting 41 (13+14+14)  O:-)   )  and in the second printf why it isn't 3?
(If it is because of the usage of stack (and/or tree) during the 
evaluation of those expressions, why dont we  get 46 in the 3rd printf 
(42 + 4) ?).

Does it depend on the compiler?
Please let me know abt the reason.
thanks in advance.

-- 
-Regards,
  Shashi.


^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: C-Query
  2004-09-15  4:23 C-Query Shashidhara S Bapat
@ 2004-09-15  4:39 ` Sriharsha Vedurmudi
  0 siblings, 0 replies; 2+ messages in thread
From: Sriharsha Vedurmudi @ 2004-09-15  4:39 UTC (permalink / raw)
  To: gcc

Shashidhara S Bapat wrote:

> Hi All,
> I have doubts in the following C program:  (I used gcc compiler)
>
> >>>
> #include <stdio.h>
>
> int main()
> {
>  int i, j,  b;
>
>  i = 12, j = 1;
>  b = ++i + ++i + i++;

Refrain from using such expressions as they are Undefined in ANSI. You 
Cannot be sure of the answer (i.e. it can vary from compiler to compiler 
and hence is not portable).

>  printf("%d\n", b);
>
>  i = 12, j = 1;
>  b = j++ + ++j;

Read Above

>  printf("%d\n", b);
>
>  i = 12, j = 1;
>  b = ++i + ++i + i++ + j++ + ++j ;

RE-READ above

>  printf("%d\n", b);
>
>  return 0;
> }
>
> and the output of the code is :
> 42
> 4
> 45.
>
> ..and my question is why do we get 42 in the first printf? (I was 
> expecting 41 (13+14+14)  O:-)   )  and in the second printf why it 
> isn't 3?
> (If it is because of the usage of stack (and/or tree) during the 
> evaluation of those expressions, why dont we  get 46 in the 3rd printf 
> (42 + 4) ?).
>
> Does it depend on the compiler?
> Please let me know abt the reason.

UNDEFINED BEHAVIOUR

> thanks in advance.
>

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2004-09-15  4:39 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2004-09-15  4:23 C-Query Shashidhara S Bapat
2004-09-15  4:39 ` C-Query Sriharsha Vedurmudi

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).