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

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

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