SlideShare a Scribd company logo
1 of 1
Download to read offline
The Joy of
Programming
  C Traps and Pitfalls:
  Swapping Two Variables                                                                                                         S.G. GANESH



  Let us look at the interesting problem of swapping two variables without using any temporary
  variables. We will discover the possible pitfalls of using smart ‘tricks’ to solve the problem. This
  column is to help students and novices understand C better.


  I
     t is assumed that the underlying machine follows 2’s                       void swap(float *i, float *j){
     complement representation for integers and IEEE 754                        *i = *i + *j;
     floating point standard for floating point numbers.                        *j = *i - *j;
      Let us look at a well-known trick of swapping two integers                *i = *i - *j;
  without using any temporary variables, which uses arithmetic                  }
  operators + and -:
                                                                                float i = FLT_MAX;
    void swap(int *i, int *j){                                                  float j = FLT_MAX;
               *i = *i + *j;                                                    printf(“Before swap : %f %fn”, i, j);
               *j = *i - *j;                                                    swap(&i, &j);
               *i = *i - *j;                                                    printf(“After swap : %f %f n”, i, j);
    }                                                                           // prints
                                                                                // Before swap : 340282346638528860000000000000000000000.000000
     Yes, we know it works. But does it really work in all cases?                                340282346638528860000000000000000000000.000000
  How about this code:                                                          // After swap : -1.#INF00 1.#INF00
GUEST COLUMN




                int arr[5] = {10,20,30,40,50};                                     Also, even for ordinary values, performing arithmetic
                int *ip = &arr[3];                                             operations can result in a loss of precision; so the swapped
                swap(ip,&arr[3]);                                              values need not be exactly the same:
                for(int i = 0; i<5; i++)
                printf(“%d “, arr[i]);                                          float i = 12345678.9f, p = i;
                // output: 10 20 30 0 50                                        float j = 98765432.1f, q = j;
                                                                                assert((i == p) && (j == q));
                    So, when the elements to be swapped happen to refer         swap(&i, &j);
               to the same location, swapping fails. In the statement ‘*i=      assert((i == q) && (j == p));
               *i + *j;’, the implicit assumption is that *i and *j point to
               two different locations; this trick will not work if the         // Assertion failed: (i == q) && (j == p), file E:tem.c, line 14
               results of + and – operations are over-written. Here is a        // abnormal program termination
               small test case just to demonstrate that:
                                                                                   You can reasonably expect that the assertion will fail in this
                int x = 10;                                                    manner for many floating point numbers because arithmetic
                printf(“before calling swap, x = %d n”, x);                   operations with floats can result in some precision loss. But it
                swap (&x, &x);                                                 won’t fail for any of the integral values, as there is no possible
                printf(“after calling swap, x = %d”, x);                       precision loss for any integral arithmetic operations.
                // prints: before calling swap, x = 10                             Another popular trick among students is to swap two
                // after calling swap, x = 0                                   variables using three repeated ex-or operations. Well, this
                                                                               solution also has many traps and pitfalls, and we’ll discuss
                 There are other problems with this swap solution              them in the next column.
  for integers, but for now, we’ll see if we can use this trick for
  swapping two floating point numbers.
       This solution doesn’t work for floats because the operation              S.G. Ganesh is an engineer in Hewlett-Packard’s C++
  ‘*i + *j’ might overflow. For integers, overflow can be                       compiler team. He has authored a book “Deep C” (ISBN 81-
  expected to result in rotation of values and it will work fine in             7656-501-6). He is also a member of the ANSI/ISO C++
                                                                                Standardisation committee (JTC1/SC22/WG21), representing
  practice (try it!); it’s not the case with floating point overflow.
                                                                                HP. You can reach him at sgganesh@gmail.com.
  The following program shows this:

                                                                                      www.linuxforu.com   |   LINUX FOR YOU     |   MAY 2007        73


                                                                       CMYK

More Related Content

What's hot (20)

Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programming
 
C operators
C operatorsC operators
C operators
 
1 introducing c language
1  introducing c language1  introducing c language
1 introducing c language
 
week-11x
week-11xweek-11x
week-11x
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
Lecture03
Lecture03Lecture03
Lecture03
 
C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5C Programming Language Step by Step Part 5
C Programming Language Step by Step Part 5
 
week-6x
week-6xweek-6x
week-6x
 
Infix to-postfix examples
Infix to-postfix examplesInfix to-postfix examples
Infix to-postfix examples
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
 
week-4x
week-4xweek-4x
week-4x
 
7 functions
7  functions7  functions
7 functions
 
6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping
 
C programming
C programmingC programming
C programming
 
Taller De Scilab
Taller De ScilabTaller De Scilab
Taller De Scilab
 
Ejercicios Scilab Completo
Ejercicios Scilab CompletoEjercicios Scilab Completo
Ejercicios Scilab Completo
 
week-23x
week-23xweek-23x
week-23x
 
Trabajo Scilab
Trabajo ScilabTrabajo Scilab
Trabajo Scilab
 
Matlab project
Matlab projectMatlab project
Matlab project
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2
 

Viewers also liked (7)

World Youth Report 2005
World Youth Report 2005World Youth Report 2005
World Youth Report 2005
 
“Cyprus Human Development Report 2009- Youth in Cyprus: Aspirations, Lifestyl...
“Cyprus Human Development Report 2009- Youth in Cyprus: Aspirations, Lifestyl...“Cyprus Human Development Report 2009- Youth in Cyprus: Aspirations, Lifestyl...
“Cyprus Human Development Report 2009- Youth in Cyprus: Aspirations, Lifestyl...
 
Salutacion Dia Del Periodista 2
Salutacion Dia Del Periodista 2Salutacion Dia Del Periodista 2
Salutacion Dia Del Periodista 2
 
2011 - Commission for Social Development, 49th Session Resolution on Policies...
2011 - Commission for Social Development, 49th Session Resolution on Policies...2011 - Commission for Social Development, 49th Session Resolution on Policies...
2011 - Commission for Social Development, 49th Session Resolution on Policies...
 
Rental villa golf riviera 5 meters to sea gh
Rental villa golf riviera 5 meters to sea ghRental villa golf riviera 5 meters to sea gh
Rental villa golf riviera 5 meters to sea gh
 
How NM Life Insurance Compares
How NM Life Insurance ComparesHow NM Life Insurance Compares
How NM Life Insurance Compares
 
Introduction
IntroductionIntroduction
Introduction
 

Similar to 05 Jo P May 07 (20)

Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
06 Jo P June 07
06 Jo P June 0706 Jo P June 07
06 Jo P June 07
 
What is c
What is cWhat is c
What is c
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C important questions
C important questionsC important questions
C important questions
 
05 operators
05   operators05   operators
05 operators
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
C tutorial
C tutorialC tutorial
C tutorial
 
22 Jop Oct 08
22 Jop Oct 0822 Jop Oct 08
22 Jop Oct 08
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Presentation1
Presentation1Presentation1
Presentation1
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
6 operators-in-c
6 operators-in-c6 operators-in-c
6 operators-in-c
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
Introduction to programming - class 3
Introduction to programming - class 3Introduction to programming - class 3
Introduction to programming - class 3
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 

More from Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Ganesh Samarthyam
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizGanesh Samarthyam
 

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

05 Jo P May 07

  • 1. The Joy of Programming C Traps and Pitfalls: Swapping Two Variables S.G. GANESH Let us look at the interesting problem of swapping two variables without using any temporary variables. We will discover the possible pitfalls of using smart ‘tricks’ to solve the problem. This column is to help students and novices understand C better. I t is assumed that the underlying machine follows 2’s void swap(float *i, float *j){ complement representation for integers and IEEE 754 *i = *i + *j; floating point standard for floating point numbers. *j = *i - *j; Let us look at a well-known trick of swapping two integers *i = *i - *j; without using any temporary variables, which uses arithmetic } operators + and -: float i = FLT_MAX; void swap(int *i, int *j){ float j = FLT_MAX; *i = *i + *j; printf(“Before swap : %f %fn”, i, j); *j = *i - *j; swap(&i, &j); *i = *i - *j; printf(“After swap : %f %f n”, i, j); } // prints // Before swap : 340282346638528860000000000000000000000.000000 Yes, we know it works. But does it really work in all cases? 340282346638528860000000000000000000000.000000 How about this code: // After swap : -1.#INF00 1.#INF00 GUEST COLUMN int arr[5] = {10,20,30,40,50}; Also, even for ordinary values, performing arithmetic int *ip = &arr[3]; operations can result in a loss of precision; so the swapped swap(ip,&arr[3]); values need not be exactly the same: for(int i = 0; i<5; i++) printf(“%d “, arr[i]); float i = 12345678.9f, p = i; // output: 10 20 30 0 50 float j = 98765432.1f, q = j; assert((i == p) && (j == q)); So, when the elements to be swapped happen to refer swap(&i, &j); to the same location, swapping fails. In the statement ‘*i= assert((i == q) && (j == p)); *i + *j;’, the implicit assumption is that *i and *j point to two different locations; this trick will not work if the // Assertion failed: (i == q) && (j == p), file E:tem.c, line 14 results of + and – operations are over-written. Here is a // abnormal program termination small test case just to demonstrate that: You can reasonably expect that the assertion will fail in this int x = 10; manner for many floating point numbers because arithmetic printf(“before calling swap, x = %d n”, x); operations with floats can result in some precision loss. But it swap (&x, &x); won’t fail for any of the integral values, as there is no possible printf(“after calling swap, x = %d”, x); precision loss for any integral arithmetic operations. // prints: before calling swap, x = 10 Another popular trick among students is to swap two // after calling swap, x = 0 variables using three repeated ex-or operations. Well, this solution also has many traps and pitfalls, and we’ll discuss There are other problems with this swap solution them in the next column. for integers, but for now, we’ll see if we can use this trick for swapping two floating point numbers. This solution doesn’t work for floats because the operation S.G. Ganesh is an engineer in Hewlett-Packard’s C++ ‘*i + *j’ might overflow. For integers, overflow can be compiler team. He has authored a book “Deep C” (ISBN 81- expected to result in rotation of values and it will work fine in 7656-501-6). He is also a member of the ANSI/ISO C++ Standardisation committee (JTC1/SC22/WG21), representing practice (try it!); it’s not the case with floating point overflow. HP. You can reach him at sgganesh@gmail.com. The following program shows this: www.linuxforu.com | LINUX FOR YOU | MAY 2007 73 CMYK