SlideShare uma empresa Scribd logo
1 de 1
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados (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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais 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
 

Mais 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
 

Último

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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
[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
 
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
 

Último (20)

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
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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 ...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
[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
 
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
 

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