SlideShare a Scribd company logo
1 of 1
Download to read offline
www.linuxforu.com | LINUX FOR YOU | JUNE 2007
C M Y K
87
I
n my previous column, we saw some of the pitfalls of using
+ and – operators to swap two variables without using a
temporary variable:
*i = *i + *j;
*j = *i - *j;
*i = *i - *j;
Think about the logic in using + and – for such
swapping. Can we use any other operators for a
similar purpose? Yes, * and / are complementary
operators and they can be used for such swapping as
well, following the same logic:
*i = *i * *j;
*j = *i / *j;
*i = *i / *j;
It works. However, this solution has two
problems: if i and j are big, then *i * *j will overflow
and by using the division operation you can’t get the
original values back; and if *j is 0, the *i / *j
expression will result in a divide by zero exception.
What about the two complementary bit-wise
operators & and | ...can we use them for swapping by
following similar logic?
*i = *i & *j;
*j = *i | *j;
*i = *i | *j;
No, it doesn’t work. Unlike + and *, the & operator is not
really an operator that retains (or accumulates) both the values
in some form that using | twice could retrieve. Try it once to
confirm it yourself.
However, the bitwise ^ can fit the requirement (though it
doesn’t have a complementary operator like + and –, * and /
operators):
*i = *i ^ *j;
*j = *i ^ *j;
*i = *i ^ *j;
It works because the ^ operator complements itself (if
either of the bits is set, the result is true, and if both bits are
same, the result is false)...it’s indeed a curious operator!
Bitwise operations are only for integral values; so this
swapping trick cannot be used for floating-point numbers.
None of the tricks we discussed will work well for swapping
two pointers. Other than binary -, no other binary arithmetic
operators (+, *, /, %) can be used for two pointers. A pointer
represents the address and subtracting two addresses is
acceptable (to see the offset or difference between the two
locations, for example, in an array), and using other arithmetic
operators with two pointers will result in compiler error. Also, it
is incorrect to apply ^ on two pointers. You can cast the
operands to integers and apply ^, but it’s a bad approach for
many reasons. For example, the conversion would fail if the
pointer and integer sizes are different.
For practical uses, it is best to stick to the plain and straight-
forward approach of using a temporary variable for swapping.
Find the bug
Here is a swap function for swapping two strings:
void swapStr(char *i, char *j){
char *temp = i;
i = j;
j = temp;
}
Looks fine and comfortable, doesn’t it? But it does not work:
char *i = “first”;
char *j = “second”;
printf(“Before swap : %s %sn”, i, j);
swapStr(i, j);
printf(“After swap : %s %sn”, i, j);
// output:
// Before swap : first second
// After swap : first second
Can you find what went wrong?
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.
The Joy of
Programming
C Traps and Pitfalls:
Swapping Two Variables–Part II
S G GaneshS G GaneshS G GaneshS G GaneshS G Ganesh is an engineer in Hewlett-Packard’s C++
compiler team. He is a member of the ANSI/ISO C++
Standardisation committee (JTC1/SC22/WG21). You can
reach him at sgganesh@gmail.com.
GUESTCOLUMN

More Related Content

What's hot

What's hot (16)

Linear algebraweek2
Linear algebraweek2Linear algebraweek2
Linear algebraweek2
 
Lesson 2-5
Lesson 2-5Lesson 2-5
Lesson 2-5
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Document
DocumentDocument
Document
 
05 operators
05   operators05   operators
05 operators
 
Antiderivatives And Slope Fields
Antiderivatives And Slope FieldsAntiderivatives And Slope Fields
Antiderivatives And Slope Fields
 
Python basic operators
Python   basic operatorsPython   basic operators
Python basic operators
 
Python operators
Python operatorsPython operators
Python operators
 
Solving Equations And Inequalities For 6th
Solving Equations And Inequalities For 6thSolving Equations And Inequalities For 6th
Solving Equations And Inequalities For 6th
 
Application of Stack, Link list , and Queue in Programming .
Application of Stack, Link list , and Queue in Programming .Application of Stack, Link list , and Queue in Programming .
Application of Stack, Link list , and Queue in Programming .
 
Java basic operators
Java basic operatorsJava basic operators
Java basic operators
 
Maths I T F
Maths  I T FMaths  I T F
Maths I T F
 
Data types and operators
Data types and operatorsData types and operators
Data types and operators
 
Matlab eig
Matlab eigMatlab eig
Matlab eig
 
R data types
R data typesR data types
R data types
 
C programming exercises and solutions
C programming exercises and solutions C programming exercises and solutions
C programming exercises and solutions
 

Viewers also liked

Viewers also liked (7)

Refactoring for design smells
Refactoring for design smellsRefactoring for design smells
Refactoring for design smells
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
7 Best Quotes on DevOps
7 Best Quotes on DevOps7 Best Quotes on DevOps
7 Best Quotes on DevOps
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle Introduction
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Atomic CLI scan
Atomic CLI scanAtomic CLI scan
Atomic CLI scan
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 

Similar to 06 Jo P June 07

Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.PVS-Studio
 
Chapter 13.1.2
Chapter 13.1.2Chapter 13.1.2
Chapter 13.1.2patcha535
 
Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Deepak Singh
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
computer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressionscomputer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressionsecomputernotes
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tourSwarup Boro
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statementsİbrahim Kürce
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Mohamed Essam
 
PVS-Studio team is about to produce a technical breakthrough, but for now let...
PVS-Studio team is about to produce a technical breakthrough, but for now let...PVS-Studio team is about to produce a technical breakthrough, but for now let...
PVS-Studio team is about to produce a technical breakthrough, but for now let...PVS-Studio
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++sanya6900
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of PrecedenceMuhammad Hammad Waseem
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and StringsIt Academy
 
computer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixcomputer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixecomputernotes
 

Similar to 06 Jo P June 07 (20)

05 Jo P May 07
05 Jo P May 0705 Jo P May 07
05 Jo P May 07
 
Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.Wade not in unknown waters. Part three.
Wade not in unknown waters. Part three.
 
Chapter 13.1.2
Chapter 13.1.2Chapter 13.1.2
Chapter 13.1.2
 
18 Jo P June 08
18 Jo P June 0818 Jo P June 08
18 Jo P June 08
 
Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Chapter 5 - Operators in C++
Chapter 5 - Operators in C++
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
computer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressionscomputer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressions
 
Chapter 1 .pptx
Chapter 1 .pptxChapter 1 .pptx
Chapter 1 .pptx
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
 
PVS-Studio team is about to produce a technical breakthrough, but for now let...
PVS-Studio team is about to produce a technical breakthrough, but for now let...PVS-Studio team is about to produce a technical breakthrough, but for now let...
PVS-Studio team is about to produce a technical breakthrough, but for now let...
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
computer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixcomputer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfix
 

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
 
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
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...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
 
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
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...Refactoring for Software Architecture Smells - International Workshop on Refa...
Refactoring for Software Architecture Smells - International Workshop on Refa...
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
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
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
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
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
#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
 
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)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
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
 
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...
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
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
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
#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
 
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 ...
 

06 Jo P June 07

  • 1. www.linuxforu.com | LINUX FOR YOU | JUNE 2007 C M Y K 87 I n my previous column, we saw some of the pitfalls of using + and – operators to swap two variables without using a temporary variable: *i = *i + *j; *j = *i - *j; *i = *i - *j; Think about the logic in using + and – for such swapping. Can we use any other operators for a similar purpose? Yes, * and / are complementary operators and they can be used for such swapping as well, following the same logic: *i = *i * *j; *j = *i / *j; *i = *i / *j; It works. However, this solution has two problems: if i and j are big, then *i * *j will overflow and by using the division operation you can’t get the original values back; and if *j is 0, the *i / *j expression will result in a divide by zero exception. What about the two complementary bit-wise operators & and | ...can we use them for swapping by following similar logic? *i = *i & *j; *j = *i | *j; *i = *i | *j; No, it doesn’t work. Unlike + and *, the & operator is not really an operator that retains (or accumulates) both the values in some form that using | twice could retrieve. Try it once to confirm it yourself. However, the bitwise ^ can fit the requirement (though it doesn’t have a complementary operator like + and –, * and / operators): *i = *i ^ *j; *j = *i ^ *j; *i = *i ^ *j; It works because the ^ operator complements itself (if either of the bits is set, the result is true, and if both bits are same, the result is false)...it’s indeed a curious operator! Bitwise operations are only for integral values; so this swapping trick cannot be used for floating-point numbers. None of the tricks we discussed will work well for swapping two pointers. Other than binary -, no other binary arithmetic operators (+, *, /, %) can be used for two pointers. A pointer represents the address and subtracting two addresses is acceptable (to see the offset or difference between the two locations, for example, in an array), and using other arithmetic operators with two pointers will result in compiler error. Also, it is incorrect to apply ^ on two pointers. You can cast the operands to integers and apply ^, but it’s a bad approach for many reasons. For example, the conversion would fail if the pointer and integer sizes are different. For practical uses, it is best to stick to the plain and straight- forward approach of using a temporary variable for swapping. Find the bug Here is a swap function for swapping two strings: void swapStr(char *i, char *j){ char *temp = i; i = j; j = temp; } Looks fine and comfortable, doesn’t it? But it does not work: char *i = “first”; char *j = “second”; printf(“Before swap : %s %sn”, i, j); swapStr(i, j); printf(“After swap : %s %sn”, i, j); // output: // Before swap : first second // After swap : first second Can you find what went wrong? 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. The Joy of Programming C Traps and Pitfalls: Swapping Two Variables–Part II S G GaneshS G GaneshS G GaneshS G GaneshS G Ganesh is an engineer in Hewlett-Packard’s C++ compiler team. He is a member of the ANSI/ISO C++ Standardisation committee (JTC1/SC22/WG21). You can reach him at sgganesh@gmail.com. GUESTCOLUMN