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

void main()
{
    int a=5,b=10,*ptr,*pt1;
    ptr=&a;
    pt1=&b;
    b=*ptr;
    a=*pt1;
    printf("%d \n %d",a,b);



}

producing same values not swapped

5
Contributors
7
Replies
9
Views
4 Years
Discussion Span
Last Post by WaltP
Featured Replies
  • 1

    And before anyone chimes in with swaps using XOR or arithmetic operators that they think are clever: your solution is bad, and you should feel bad. Read More

  • 2

    > why one should not use XoR or arithmetic operation to swap number??? Because it's inferior to using a temporary variable, and the original reason for avoiding a temporary variable is totally irrelevant unless you're on a severely memory constrained platform. And by "severely", I mean so much that you … Read More

1

And before anyone chimes in with swaps using XOR or arithmetic operators that they think are clever: your solution is bad, and you should feel bad.

Votes + Comments
Nice. And correct!
0

Hi Deceptikon,

And before anyone chimes in with swaps using XOR or arithmetic operators that they think are clever: your solution is bad, and you should feel bad.

why one should not use XoR or arithmetic operation to swap number??? can you please explain it?
Then how to swap numbers without using temparory variable.

Edited by Perry31

2

why one should not use XoR or arithmetic operation to swap number???

Because it's inferior to using a temporary variable, and the original reason for avoiding a temporary variable is totally irrelevant unless you're on a severely memory constrained platform. And by "severely", I mean so much that you actually map out your register usage and design algorithms to avoid stack or heap use. Oh, and this also assumes that you're writing your code directly in assembly because C is just too heavy.

Then how to swap numbers without using temparory variable.

http://en.wikipedia.org/wiki/XOR_swap_algorithm

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

    void main()
    {
    int a=5,b=10,*ptr,*pt1;
   *ptr=a+b-a;
   *pt1=a+b-b;
   a=*ptr;
   b=*pt1;
   printf("%d",a);
   printf("%d",a);


  }

will this work sir????

Edited by rithish

0

sigh

This will work and is correct:

#include <stdio.h>

int main(void)
{
    int a = 5, b = 10;
    int temp;

    printf("%d %d\n", a, b);

    temp = a;
    a = b;
    b = temp;

    printf("%d %d\n", a, b);

    return 0;
}
0

will this work sir????

What part of

you need to use an intermediate integer.

int a,b,temp;

temp = a
a = b
b = temp

did you not understand?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.