SlideShare une entreprise Scribd logo
1  sur  1
Télécharger pour lire hors ligne
The Joy of
Programming                                                                                                             S.G. GaneSh

Duff’s Device and Some Interesting Aspects of Switch
The switch statement appears mundane; what can be special or interesting about it? In this issue, we’ll
explore the switch statement—you may realise that you’ve underestimated its value!


C
         /C++ allows only integer types for use in case              send(short *to, short *from, int count){
         statements. Why can’t we use floating point numbers?                 do
         Because C designers thought that it is not a good idea:                         *to = *from++;
checking the exact equality in floating point is not portable                 while(--count>0);
[ref: C99 rationale]. How about string literals? It is allowed in    }   // this program fails if count is equal to zero.
many languages that evolved from C, such as C#, which is a             and this version, compiled in a VAX C compiler, ran
useful feature. Since switch is for integral types, a compiler      very slow. The reason is that the compiler translates
can translate it to efficient code, as we will now see.             do-while as a pair of two gotos and labels (one for each
     Which of the two is better: a switch statement or              true and false case); for every condition check, a goto is
cascading if-else statements? Well, a switch expresses              executed, which makes it slow. So Tom Duff proposed
the programmer’s intentions more clearly than an if-else            another, faster version:
cascade. Also, you might be surprised to know that a switch               send(short *to, short *from, int count){
is, in general, more efficient than an equivalent if-else             register n=(count+7)/8;
statement sequence! Why?                                              // get number of times to execute do...while loop
     The if-else statement is flexible: it can have different         switch(count%8){
conditions for each ‘if’ statement; also each condition can                   // go to the remaining mod value
have (different) variables for comparison in the conditional                  case 0: do{ *to = *from++;
expression. However, a switch statement is limited: it can                    case 7: *to = *from++;
have only one condition and the matching of the case                          case 6: *to = *from++;
statements to the condition expression is always an equality                  case 5: *to = *from++;
comparison; the case statements are always constant values                    case 4: *to = *from++;
(and not variables). Because of these reasons, the compiler                   case 3: *to = *from++;
can do a better job and generate efficient code. How?                         case 2: *to = *from++;
     A sequence of if-else statements is typically translated                 case 1: *to = *from++;
as a sequence of labels and jump statements (gotos). For a                    }while(--n>0);
switch statement, a compiler generates an internal table to                   // this loop is executed n times
find the matches at runtime. Depending on the constants                  }
in the case statements, the table can be a look-up or range          }
table. If the constants are unrelated, the comparison is             // this program fails if count is equal to zero.
usually done at the beginning and the jump is made to                   The idea is to find out the number of times the loop is to
the specific entry in the table (i.e., a look-up table). If         be executed in n and call switch to copy for modulus value.
the constants are related and within a range (e.g., ‘0’ to          The do-while loop just ignores the case statements since
‘9’), the jump can be made for each range of values (i.e.,          they are just labels. This technique exploits the fact that
a range table). For example, a Java compiler internally             case statements do not break automatically. This version
compiles the switch statements into either lookupswitch             ran faster than the do-while loop version (one goto for one
or tableswitch bytecodes. So the switch is typically more           statement) because this version has less gotos (only one
efficient than if-else statements (unless the compiler is           goto for 8 statements) when the compiler translates it.
very smart, which is unlikely). The efficiency of switch                Even though this technique clearly exploits the fall
statements is often exploited in different techniques and           through nature of C switch statements, it is (fortunately)
we’ll now look at an unusual case.                                  not widely used; it is good to be aware of this technique,
     A source of nasty bugs in C-based languages is that            but don’t use it!
the case statements in the switch statement are fall-
through. The ‘fall-through’ nature of switch is exploited in a       S.G. Ganesh is a research engineer in Siemens (Corporate
technique called as Duff’s device [Tom Duff, ‘netnews’, May          Technology). His latest book is “60 Tips on Object Oriented
                                                                     Programming”, published by Tata McGraw-Hill. You can
1984]. The following function which copies count number
                                                                     reach him at sgganesh@gmail.com
of bytes pointed by from to to:


106    September 2008   |   LINUX For YoU   |   www.openItis.com

Contenu connexe

Tendances (19)

C programming part4
C programming part4C programming part4
C programming part4
 
The Loops
The LoopsThe Loops
The Loops
 
Loops c++
Loops c++Loops c++
Loops c++
 
Final requirement
Final requirementFinal requirement
Final requirement
 
C++ loop
C++ loop C++ loop
C++ loop
 
Loops
LoopsLoops
Loops
 
Function procedure c6 c7
Function procedure  c6 c7Function procedure  c6 c7
Function procedure c6 c7
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
C++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variablesC++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variables
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Basic c# cheat sheet
Basic c# cheat sheetBasic c# cheat sheet
Basic c# cheat sheet
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
Type Conversion in C++ and C# Arithmetic Expressions
Type Conversion in C++ and C# Arithmetic ExpressionsType Conversion in C++ and C# Arithmetic Expressions
Type Conversion in C++ and C# Arithmetic Expressions
 
Control statements
Control statementsControl statements
Control statements
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
C programming session5
C programming  session5C programming  session5
C programming session5
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
Session 5-exersice
Session 5-exersiceSession 5-exersice
Session 5-exersice
 

En vedette (15)

21 Jo P Sept 08
21 Jo P Sept 0821 Jo P Sept 08
21 Jo P Sept 08
 
05 Jo P May 07
05 Jo P May 0705 Jo P May 07
05 Jo P May 07
 
Question
QuestionQuestion
Question
 
Eend
EendEend
Eend
 
10 Jo P Oct 07
10 Jo P Oct 0710 Jo P Oct 07
10 Jo P Oct 07
 
“African Youth Report 2009: Expanding opportunities for and with Young people...
“African Youth Report 2009: Expanding opportunities for and with Young people...“African Youth Report 2009: Expanding opportunities for and with Young people...
“African Youth Report 2009: Expanding opportunities for and with Young people...
 
Presentación1
Presentación1Presentación1
Presentación1
 
New Text Document
New Text DocumentNew Text Document
New Text Document
 
Starting The Bloggg
Starting The BlogggStarting The Bloggg
Starting The Bloggg
 
Roset 1
Roset 1Roset 1
Roset 1
 
Murray's Equality of the Sexes
Murray's Equality of the SexesMurray's Equality of the Sexes
Murray's Equality of the Sexes
 
Examen R 2
Examen R 2Examen R 2
Examen R 2
 
Golf yatirimci kilavuzu
Golf yatirimci kilavuzuGolf yatirimci kilavuzu
Golf yatirimci kilavuzu
 
Dardin
DardinDardin
Dardin
 
Card Pack Ad
Card Pack AdCard Pack Ad
Card Pack Ad
 

Similaire à 22 Jop Oct 08

Writing Efficient Code Feb 08
Writing Efficient Code Feb 08Writing Efficient Code Feb 08
Writing Efficient Code Feb 08Ganesh Samarthyam
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping newaprilyyy
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.gerrell
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kimkimberly_Bm10203
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!olracoatalub
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptBinu Paul
 
JavaScript: Core Part
JavaScript: Core PartJavaScript: Core Part
JavaScript: Core Part維佋 唐
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
Inline function
Inline functionInline function
Inline functionTech_MX
 

Similaire à 22 Jop Oct 08 (20)

Writing Efficient Code Feb 08
Writing Efficient Code Feb 08Writing Efficient Code Feb 08
Writing Efficient Code Feb 08
 
Go1
Go1Go1
Go1
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
My final requirement
My final requirementMy final requirement
My final requirement
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kim
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to Javascript
 
Matopt
MatoptMatopt
Matopt
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C++ programming
C++ programmingC++ programming
C++ programming
 
JavaScript: Core Part
JavaScript: Core PartJavaScript: Core Part
JavaScript: Core Part
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Analyzing algorithms
Analyzing algorithmsAnalyzing algorithms
Analyzing algorithms
 
Inline function
Inline functionInline function
Inline function
 
Survelaine murillo ppt
Survelaine murillo pptSurvelaine murillo ppt
Survelaine murillo ppt
 

Plus de 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
 

Plus de 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
 

Dernier

[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
 
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
 
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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
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
 
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
 
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
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
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
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
#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
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Dernier (20)

[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
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
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
 
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
 
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
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
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
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
#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
 
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
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

22 Jop Oct 08

  • 1. The Joy of Programming S.G. GaneSh Duff’s Device and Some Interesting Aspects of Switch The switch statement appears mundane; what can be special or interesting about it? In this issue, we’ll explore the switch statement—you may realise that you’ve underestimated its value! C /C++ allows only integer types for use in case send(short *to, short *from, int count){ statements. Why can’t we use floating point numbers? do Because C designers thought that it is not a good idea: *to = *from++; checking the exact equality in floating point is not portable while(--count>0); [ref: C99 rationale]. How about string literals? It is allowed in } // this program fails if count is equal to zero. many languages that evolved from C, such as C#, which is a and this version, compiled in a VAX C compiler, ran useful feature. Since switch is for integral types, a compiler very slow. The reason is that the compiler translates can translate it to efficient code, as we will now see. do-while as a pair of two gotos and labels (one for each Which of the two is better: a switch statement or true and false case); for every condition check, a goto is cascading if-else statements? Well, a switch expresses executed, which makes it slow. So Tom Duff proposed the programmer’s intentions more clearly than an if-else another, faster version: cascade. Also, you might be surprised to know that a switch send(short *to, short *from, int count){ is, in general, more efficient than an equivalent if-else register n=(count+7)/8; statement sequence! Why? // get number of times to execute do...while loop The if-else statement is flexible: it can have different switch(count%8){ conditions for each ‘if’ statement; also each condition can // go to the remaining mod value have (different) variables for comparison in the conditional case 0: do{ *to = *from++; expression. However, a switch statement is limited: it can case 7: *to = *from++; have only one condition and the matching of the case case 6: *to = *from++; statements to the condition expression is always an equality case 5: *to = *from++; comparison; the case statements are always constant values case 4: *to = *from++; (and not variables). Because of these reasons, the compiler case 3: *to = *from++; can do a better job and generate efficient code. How? case 2: *to = *from++; A sequence of if-else statements is typically translated case 1: *to = *from++; as a sequence of labels and jump statements (gotos). For a }while(--n>0); switch statement, a compiler generates an internal table to // this loop is executed n times find the matches at runtime. Depending on the constants } in the case statements, the table can be a look-up or range } table. If the constants are unrelated, the comparison is // this program fails if count is equal to zero. usually done at the beginning and the jump is made to The idea is to find out the number of times the loop is to the specific entry in the table (i.e., a look-up table). If be executed in n and call switch to copy for modulus value. the constants are related and within a range (e.g., ‘0’ to The do-while loop just ignores the case statements since ‘9’), the jump can be made for each range of values (i.e., they are just labels. This technique exploits the fact that a range table). For example, a Java compiler internally case statements do not break automatically. This version compiles the switch statements into either lookupswitch ran faster than the do-while loop version (one goto for one or tableswitch bytecodes. So the switch is typically more statement) because this version has less gotos (only one efficient than if-else statements (unless the compiler is goto for 8 statements) when the compiler translates it. very smart, which is unlikely). The efficiency of switch Even though this technique clearly exploits the fall statements is often exploited in different techniques and through nature of C switch statements, it is (fortunately) we’ll now look at an unusual case. not widely used; it is good to be aware of this technique, A source of nasty bugs in C-based languages is that but don’t use it! the case statements in the switch statement are fall- through. The ‘fall-through’ nature of switch is exploited in a S.G. Ganesh is a research engineer in Siemens (Corporate technique called as Duff’s device [Tom Duff, ‘netnews’, May Technology). His latest book is “60 Tips on Object Oriented Programming”, published by Tata McGraw-Hill. You can 1984]. The following function which copies count number reach him at sgganesh@gmail.com of bytes pointed by from to to: 106 September 2008 | LINUX For YoU | www.openItis.com