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

Infix to-postfix examples
Infix to-postfix examplesInfix to-postfix examples
Infix to-postfix examples
mua99
 
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
alish sha
 

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

Salutacion Dia Del Periodista 2
Salutacion Dia Del Periodista 2Salutacion Dia Del Periodista 2
Salutacion Dia Del Periodista 2
guest2e5897
 

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

C programming session 02
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
Amit Kapoor
 

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

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

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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