SlideShare a Scribd company logo
The Joy of
Programming
Some Interesting Programming Puzzles                                                                             S.G. GANESH

Every experienced C programmer knows that if the code looks simple, straightforward and perfectly
fine, it doesn’t necessarily mean that it would work fine and not dump-core at runtime! In this
month’s column, we’ll look at a few such interesting programming problems.

     1) This program had an assertion failure. Why?                   Avoid looking at the answers immediately; instead, try to
 struct bitfield {                                               solve them first.
     signed int b : 1;                                                Solution 1: A signed bit-field size of 1 can store only one
 } bit;                                                          bit, and that value becomes a sign bit. For storing the value 1,
                                                                 the only bit available is used, which is the sign bit. So, 1
 int main() {                                                    becomes -1 for a bit-field member of size 1. If you use
     bit.b = 1;                                                  “printf(“%d”, bit.b)”, you would see the output -1.
     assert(bit.b == 1);                                              Solution 2: This condition fails when i is INT_MIN.
 }                                                               Remember that the range of an integer is 2(n-1) to 2(n-1)-1, where
                                                                 n is the size of the integer. INT_MIN is the least possible value
    2) This function worked fine for many years and              of integral negative numbers and when we negate it, as in -i, it
suddenly, for some value of i, the assertion failed. What was    is not in the range of positive integers. So, it ‘overflows’ and
that value of i for which it failed and why?                     becomes negative and INT_MIN again! So the assertion fails.
     int my_abs(int i) {                                              Solution 3: For NaN (Not a Number), the condition (d ==
          if (i < 0) {                                           d) is not true! The IEEE 754 floating point arithmetic standard
              i = -i;                                            has a special number called NaN for representing invalid
          }                                                      values like (0.0/0.0) instead of just throwing an error/exception
          assert(i >= 0);                                        like Divide-by-Zero. To detect this special number
          return i;                                              programmatically, the special condition of (NaN != NaN) is
     }                                                           provided.
                                                                      Solution 4: The prototype for the sqrt library function is
    3) The following function was written with an intention      missing in this program. For those functions that are not
that the printf should never be executed. But for some value     declared (but used), the compiler assumes the return type to
of d, the message got printed! What is that value of ‘d’?        be int. Since <math.h> is not included in this program (which
 void oops(double d) {                                           has the prototype for sqrt), sqrt is assumed to return int; the
     if(d != d)                                                  actual double value that is returned from sqrt(2) is converted
          printf(“Oops! Something went wrong”);                  to an int value and assigned to x after casting it to double.
 }                                                               This results in the wrong output. The solution is to either use
                                                                 #include <math.h> or provide the prototype of sqrt before
    4) The following program, when run, gave the output:         its use.
sqrt of 2=1557547102.000000 instead of: sqrt of 2=1.414214.           Solution 5: The character ‘hi’ is a multi-byte character,
What could be the problem?                                       and the programmer has typed ‘hi’ instead of “hi” (typing ‘,
 int main() {                                                    instead of “ , by mistake). The printf function tries to
     double x = sqrt(2);                                         interpret msg as if it is pointing to a string literal, and reads
     printf(quot;sqrt of 2=%lfquot;, x);                                 that address, which is grossly incorrect; hence the program
 }                                                               core-dumped...
                                                                      That’s it for now. And here’s wishing you a happy
    5) This program core-dumped at runtime instead of            new year!
printing “hi”; can you find out why?
 int main() {
                                                                  S G Ganesh is a research engineer in Siemens (Corporate
                                                                  Technology). His latest book is “60 Tips on Object Oriented
     char * msg = ‘hi’;
                                                                  Programming”, published by Tata-McGraw Hill in
     printf(msg);                                                 December, 2007. You can reach him at
 }                                                                sgganesh@gmail.com.



                                                                    www.linuxforu.com   |   LINUX FOR YOU   |   JANUARY 2008   127


                                                          CMYK

More Related Content

What's hot

100 c interview questions answers
100 c interview questions answers100 c interview questions answers
100 c interview questions answersSareen Kumar
 
C programming session 07
C programming session 07C programming session 07
C programming session 07AjayBahoriya
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
[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++
Muhammad Hammad Waseem
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
Pointers in C language
Pointers  in  C languagePointers  in  C language
Pointers in C language
Infinity Tech Solutions
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
rgnikate
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3
YOGESH SINGH
 
10 -bits_and_bytes
10  -bits_and_bytes10  -bits_and_bytes
10 -bits_and_bytesHector Garzo
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
C++ Homework Help
 
Pointer in C
Pointer in CPointer in C
Pointer in C
Sonya Akter Rupa
 
C programming part4
C programming part4C programming part4
C programming part4
Keroles karam khalil
 

What's hot (20)

100 c interview questions answers
100 c interview questions answers100 c interview questions answers
100 c interview questions answers
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
 
02 Jo P Feb 07
02 Jo P Feb 0702 Jo P Feb 07
02 Jo P Feb 07
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
[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++
 
22 Jop Oct 08
22 Jop Oct 0822 Jop Oct 08
22 Jop Oct 08
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
Pointers in C language
Pointers  in  C languagePointers  in  C language
Pointers in C language
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3
 
10 -bits_and_bytes
10  -bits_and_bytes10  -bits_and_bytes
10 -bits_and_bytes
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
C programming part4
C programming part4C programming part4
C programming part4
 

Viewers also liked

Ee463 ofdm - loren schwappach
Ee463   ofdm - loren schwappachEe463   ofdm - loren schwappach
Ee463 ofdm - loren schwappachLoren Schwappach
 
World Programme of Action for Youth
World Programme of Action for YouthWorld Programme of Action for Youth
Peachs neet feet
Peachs neet feetPeachs neet feet
Peachs neet feetRylee Smith
 
Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)
Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)
Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)
European Economic and Social Committee - SOC Section
 
Social media and socio analysis - BETA
Social media and socio analysis - BETASocial media and socio analysis - BETA
Social media and socio analysis - BETADavid Patman
 
Customer Success Applied Outside the Box
Customer Success Applied Outside the BoxCustomer Success Applied Outside the Box
Customer Success Applied Outside the Box
Totango
 
Php
PhpPhp
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
 

Viewers also liked (9)

Ooievaar
OoievaarOoievaar
Ooievaar
 
Ee463 ofdm - loren schwappach
Ee463   ofdm - loren schwappachEe463   ofdm - loren schwappach
Ee463 ofdm - loren schwappach
 
World Programme of Action for Youth
World Programme of Action for YouthWorld Programme of Action for Youth
World Programme of Action for Youth
 
Peachs neet feet
Peachs neet feetPeachs neet feet
Peachs neet feet
 
Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)
Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)
Fragen an die Experten des Hearings in der Studiengruppe zu SOC/472 (1,4-11)
 
Social media and socio analysis - BETA
Social media and socio analysis - BETASocial media and socio analysis - BETA
Social media and socio analysis - BETA
 
Customer Success Applied Outside the Box
Customer Success Applied Outside the BoxCustomer Success Applied Outside the Box
Customer Success Applied Outside the Box
 
Php
PhpPhp
Php
 
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)
 

Similar to 13 Jo P Jan 08

C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
C++ Homework Help
 
1 ECE 175 Computer Programming for Engineering Applica.docx
1  ECE 175 Computer Programming for Engineering Applica.docx1  ECE 175 Computer Programming for Engineering Applica.docx
1 ECE 175 Computer Programming for Engineering Applica.docx
oswald1horne84988
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
David Halliday
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
David Halliday
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit Issues
Andrey Karpov
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errors
PVS-Studio
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103Sure Interview
 
if, while and for in Python
if, while and for in Pythonif, while and for in Python
if, while and for in Python
PranavSB
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
HNDE Labuduwa Galle
 
Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++Mohammed Nisamudheen
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
Mosky Liu
 
C Language Unit-1
C Language Unit-1C Language Unit-1
C Language Unit-1
kasaragadda srinivasrao
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
josies1
 
Dr Mrs A A Miraje C Programming PPT.pptx
Dr Mrs A A Miraje C Programming PPT.pptxDr Mrs A A Miraje C Programming PPT.pptx
Dr Mrs A A Miraje C Programming PPT.pptx
ProfAAMiraje
 
I need help getting my mips program completed this are the full inst.pdf
I need help getting my mips program completed this are the full inst.pdfI need help getting my mips program completed this are the full inst.pdf
I need help getting my mips program completed this are the full inst.pdf
allurafashions98
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 

Similar to 13 Jo P Jan 08 (20)

C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
2 debugging-c
2 debugging-c2 debugging-c
2 debugging-c
 
1 ECE 175 Computer Programming for Engineering Applica.docx
1  ECE 175 Computer Programming for Engineering Applica.docx1  ECE 175 Computer Programming for Engineering Applica.docx
1 ECE 175 Computer Programming for Engineering Applica.docx
 
17 Jo P May 08
17 Jo P May 0817 Jo P May 08
17 Jo P May 08
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
C++11 and 64-bit Issues
C++11 and 64-bit IssuesC++11 and 64-bit Issues
C++11 and 64-bit Issues
 
26 Jo P Feb 09
26 Jo P Feb 0926 Jo P Feb 09
26 Jo P Feb 09
 
Optimization in the world of 64-bit errors
Optimization  in the world of 64-bit errorsOptimization  in the world of 64-bit errors
Optimization in the world of 64-bit errors
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
if, while and for in Python
if, while and for in Pythonif, while and for in Python
if, while and for in Python
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++Concept_of_NAN_IND_INF_DEN_Using_C++
Concept_of_NAN_IND_INF_DEN_Using_C++
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
C Language Unit-1
C Language Unit-1C Language Unit-1
C Language Unit-1
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
Dr Mrs A A Miraje C Programming PPT.pptx
Dr Mrs A A Miraje C Programming PPT.pptxDr Mrs A A Miraje C Programming PPT.pptx
Dr Mrs A A Miraje C Programming PPT.pptx
 
I need help getting my mips program completed this are the full inst.pdf
I need help getting my mips program completed this are the full inst.pdfI need help getting my mips program completed this are the full inst.pdf
I need help getting my mips program completed this are the full inst.pdf
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 

More from Ganesh Samarthyam

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
Ganesh Samarthyam
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
Ganesh Samarthyam
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
Ganesh 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 Enough
Ganesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh 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 Examples
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
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 Deck
Ganesh 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 Language
Ganesh 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 Questions
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
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 quiz
Ganesh Samarthyam
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
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
 
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
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 

Recently uploaded

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 

Recently uploaded (20)

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 

13 Jo P Jan 08

  • 1. The Joy of Programming Some Interesting Programming Puzzles S.G. GANESH Every experienced C programmer knows that if the code looks simple, straightforward and perfectly fine, it doesn’t necessarily mean that it would work fine and not dump-core at runtime! In this month’s column, we’ll look at a few such interesting programming problems. 1) This program had an assertion failure. Why? Avoid looking at the answers immediately; instead, try to struct bitfield { solve them first. signed int b : 1; Solution 1: A signed bit-field size of 1 can store only one } bit; bit, and that value becomes a sign bit. For storing the value 1, the only bit available is used, which is the sign bit. So, 1 int main() { becomes -1 for a bit-field member of size 1. If you use bit.b = 1; “printf(“%d”, bit.b)”, you would see the output -1. assert(bit.b == 1); Solution 2: This condition fails when i is INT_MIN. } Remember that the range of an integer is 2(n-1) to 2(n-1)-1, where n is the size of the integer. INT_MIN is the least possible value 2) This function worked fine for many years and of integral negative numbers and when we negate it, as in -i, it suddenly, for some value of i, the assertion failed. What was is not in the range of positive integers. So, it ‘overflows’ and that value of i for which it failed and why? becomes negative and INT_MIN again! So the assertion fails. int my_abs(int i) { Solution 3: For NaN (Not a Number), the condition (d == if (i < 0) { d) is not true! The IEEE 754 floating point arithmetic standard i = -i; has a special number called NaN for representing invalid } values like (0.0/0.0) instead of just throwing an error/exception assert(i >= 0); like Divide-by-Zero. To detect this special number return i; programmatically, the special condition of (NaN != NaN) is } provided. Solution 4: The prototype for the sqrt library function is 3) The following function was written with an intention missing in this program. For those functions that are not that the printf should never be executed. But for some value declared (but used), the compiler assumes the return type to of d, the message got printed! What is that value of ‘d’? be int. Since <math.h> is not included in this program (which void oops(double d) { has the prototype for sqrt), sqrt is assumed to return int; the if(d != d) actual double value that is returned from sqrt(2) is converted printf(“Oops! Something went wrong”); to an int value and assigned to x after casting it to double. } This results in the wrong output. The solution is to either use #include <math.h> or provide the prototype of sqrt before 4) The following program, when run, gave the output: its use. sqrt of 2=1557547102.000000 instead of: sqrt of 2=1.414214. Solution 5: The character ‘hi’ is a multi-byte character, What could be the problem? and the programmer has typed ‘hi’ instead of “hi” (typing ‘, int main() { instead of “ , by mistake). The printf function tries to double x = sqrt(2); interpret msg as if it is pointing to a string literal, and reads printf(quot;sqrt of 2=%lfquot;, x); that address, which is grossly incorrect; hence the program } core-dumped... That’s it for now. And here’s wishing you a happy 5) This program core-dumped at runtime instead of new year! printing “hi”; can you find out why? int main() { S G Ganesh is a research engineer in Siemens (Corporate Technology). His latest book is “60 Tips on Object Oriented char * msg = ‘hi’; Programming”, published by Tata-McGraw Hill in printf(msg); December, 2007. You can reach him at } sgganesh@gmail.com. www.linuxforu.com | LINUX FOR YOU | JANUARY 2008 127 CMYK