c articles

Upload: xalembk

Post on 08-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 C Articles

    1/54

    Menu

    Distinguish between pointers and references in C++ ......................................................................2

    Comparison of popular compilers and IDEs ...................................................................................5Book Of Brilliant Things ................................................................................................................ 9

    Contents: ..................................................................................................................................... 9Subject: C++ ............................................................................................................................. 10

    Subject: Algorithms and Data Structures ..................................................................................18

    Copy constructors, assignment operators, and exception safe assignment ...................................20What is a copy constructor? ......................................................................................................20

    When do I need to write a copy constructor? ............................................................................22

    First, you should understand that if you do not declare a copy constructor, the compiler givesyou one implicitly. The implicit copy constructor does a member-wise copy of the source

    object......................................................................................................................................... 22

    For example, given the class: ....................................................................................................22Const correctness ...................................................................................................................... 23What is an assignment operator? .............................................................................................. 25

    When do I need to write an assignment operator? .................................................................... 26

    What is meant by Exception Safe code? ...................................................................................27How do I write an exception safe assignment operator? .......................................................... 30

    How to use tags ............................................................................................................................. 32

    1.) Source Code Tags ................................................................................................................ 322.) Output Tags ......................................................................................................................... 33

    1/2.) Combining the Above ...................................................................................................34

    3.) Quotation Tags .....................................................................................................................34

    4.) Teletype Tags .......................................................................................................................355.) Miscellaneous Tags ............................................................................................................. 35

    6.) More Information .................................................................................................................36

    Converting numbers to strings and strings to numbers .................................................................36Contents: ................................................................................................................................... 36

    C++ - stringstreams ...................................................................................................................37

    Number to String .......................................................................................................................37Custom formatting .................................................................................................................... 38

    String to Number .......................................................................................................................40

    More complex cases ..................................................................................................................41

    Simple Sample Functions ..........................................................................................................41

    C++ - Boost Library ..................................................................................................................42C - stdio .....................................................................................................................................43

    Number to String ...................................................................................................................43String to Number ...................................................................................................................44

    C stdlib ...................................................................................................................................45

    Writing your own function ........................................................................................................45How To: Ask Questions The Smart Way ......................................................................................48

    Introduction ...............................................................................................................................48

    1

  • 8/6/2019 C Articles

    2/54

    Before You Ask ........................................................................................................................ 48

    When You Ask ..........................................................................................................................49

    When asking about code ........................................................................................................... 51Don't post homework questions ................................................................................................ 52

    Follow up with a brief note on the solution .............................................................................. 52

    How To Interpret Answers ........................................................................................................52How To Answer Questions in a Helpful Way .......................................................................... 53

    Distinguish between pointers and references in C++

    Published by EliteHussar

    Last update on Aug 20, 2010 at 6:10am UTC

    Pointers and references look different enough (pointers use the * and -> operators,

    references use .), but they seem to do similar things. Both pointers and references let

    you refer to other objects indirectly. How, then, do you decide when to use one and not

    the other?

    First, recognize that there is no such thing as a null reference. A reference must always

    refer to some object. As a result, if you have a variable whose purpose is to refer to

    another object, but it is possible that there might not be an object to refer to, you should

    make the variable a pointer, because then you can set it to null. On the other hand, if the

    variable must always refer to an object, i.e., if your design does not allow for the

    possibility that the variable is null, you should probably make the variable a reference.

    But wait, you wonder, what about underhandedness like this?

    1 char*pc = 0; // set pointer to null

    2

    http://cplusplus.com/member/EliteHussar/http://learnbyexamples.org/cc/distinguish-between-pointers-and-references-in-c.htmlhttp://cplusplus.com/member/EliteHussar/http://learnbyexamples.org/cc/distinguish-between-pointers-and-references-in-c.html
  • 8/6/2019 C Articles

    3/54

    2

    3

    char& rc = *pc; // make reference refer to

    // dereferenced null pointer

    Well, this is evil, pure and simple. The results are undefined (compilers can generate

    output to do anything they like), and people who write this kind of code should be

    shunned until they agree to cease and desist. If you have to worry about things like this

    in your software, youre probably best off avoiding references entirely. Either that or

    finding a better class ofprogrammers to work with. Well henceforth ignore the

    possibility that a reference can be null.

    Because a reference must refer to an object, C++ requires that references be initialized:1

    2

    3

    4

    string& rs; // error! References must

    // be initialized

    string s("xyzzy");

    string& rs = s; // okay, rs refers to s

    Pointers are subject to no such restriction:

    12

    string *ps; // uninitialized pointer:// valid but risky

    The fact that there is no such thing as a null reference implies that it can be more

    efficient to use references than to use pointers. Thats because theres no need to test the

    validity of a reference before using it:

    1

    2

    3

    4

    void printDouble(constdouble& rd)

    {

    cout

  • 8/6/2019 C Articles

    4/54

    2

    3

    4

    56

    {

    if(pd) { // check for null pointer

    cout

  • 8/6/2019 C Articles

    5/54

  • 8/6/2019 C Articles

    6/54

    People often confuse the difference between a 'compiler' and an 'IDE', which I guess is

    born from the fact that most IDEs come with a compiler.

    Compilers

    A compiler is a program which takes source code written by a programmer and creates

    an executable file.

    Different compilers do this in different ways -- many compilers consist of

    a compiler, assembler and linker, although some do the assembling and linking

    themselves.

    A compiler, then, must create assembly code from the source code given and pass it to

    the assembler. The assembler creates object code from the assembly code and then

    passes the object files on to the linker. The linker finally creates the exectuable file that

    you can run.

    IDEs

    IDE can either stand for Integrated Drive Electronics (which is a totally irrelevant (and

    far more complicated) topic) or Integrated Development Environment.

    An IDE is a program or (more usually) a group of programs which are used for program

    development. An IDE usually consists of a syntax-highlighting text editor and a lot of

    buttons and toolbars and such to help you to write code efficiently.

    IDEs often come bundled with a compiler suite as well as a debugger and some have

    more advanced features such as find-and-replace and auto-completion.

    6

  • 8/6/2019 C Articles

    7/54

    Comparisons

    Compilers

    There are many popular compilers, among them the GNU Compiler Collection (GCC)which includes gcc and g++ (the GNU C Compiler and GNU C++ Compiler) and

    Microsoft's Visual C and Visual C++ compilers. There are many other compilers of

    varying qualities, such as the Borland C/C++ compilers, the Intel C++ compiler and the

    [Open]Watcom Compilers. We will focus on gcc and Visual C in this article as they are

    the most popular compilers.

    gcc/g++

    Free/Open-Source -- gcc can be modified, derived or redistributed

    by anyone given that the modified/derivied/redistributed version remains licensed

    under the GNU General Public License (GPL)

    Cross-platform -- as gcc is open source, it has successfully been ported to various

    platforms including Linux, Microsoft Windows and Mac OS. If you are a Linux

    user you almost certainly have gcc installed already. You may have to install g++separately, in which case you should use your distribution's package manager or

    download the source code. On Windows, you can find gcc in the MinGW and

    Cygwin packages.

    Fast -- as a modern, optimizing compiler gcc produces relatively efficient code

    Note: gcc and g++ should not be capitalized (to distinguish gcc from GCC).

    Microsoft Visual C/C++

    7

  • 8/6/2019 C Articles

    8/54

    Free -- a version of Visual C/C++ (which may or may not be crippleware) is

    available for commercial use from Microsoft's website.

    Debugger -- Visual C/C++ is often acclaimed for it's powerful debugger.

    Others

    Other compilers also exist. Among these are OpenWatcom and the Intel C++ Compiler.

    OpenWatcom is a cross-platform (Windows, MS-DOS, Linux and others) optimizing

    compiler which can produce 16-bit code (something gcc cannot do). The Intel C++

    compiler provides very thorough optimization.

    IDEs

    Popular IDEs include

    Dev-C++ (note: you are recommended to use wxDev-C++ instead as Dev-C++

    has not been updated for 5 years)

    Code::Blocks

    Netbeans

    Microsoft Visual Studio

    Eclipse

    KDevelop

    Errata

    Regarding Visual C/C++ -- This is now free for commercial use (thanks to PGP

    Protector)

    8

  • 8/6/2019 C Articles

    9/54

    Book Of Brilliant Things

    Published by Grey Wolf

    Last update on Jun 25, 2010 at 9:22am UTC

    I would love to take a look

    Into the bright and shiny book

    Into the open scheme of things

    Book of brilliant things.

    The list off books presented here are, in my experience, highly regarded in the

    programming community. I do not present them in any order of merit, but I will try to

    keep them in some logical order, by subject covered and experience level.

    The Text about the books is cribbed from either the back cover of the book or Amazon's

    description. I hope this does not cause a problem with copyright.

    Contents:

    Subject: C++

    o Beginner books

    o Intermediate and expert books

    Subject: Algorithms and Data Structures

    o Beginner books

    o Intermediate and expert books

    9

    http://cplusplus.com/member/Grey_Wolf/http://cplusplus.com/articles/Book_Of_Brilliant_Things/#CPPhttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#CPP-Beghttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#CPP-Inthttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#ALGhttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#ALG-Beghttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#ALG-Inthttp://cplusplus.com/member/Grey_Wolf/http://cplusplus.com/articles/Book_Of_Brilliant_Things/#CPPhttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#CPP-Beghttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#CPP-Inthttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#ALGhttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#ALG-Beghttp://cplusplus.com/articles/Book_Of_Brilliant_Things/#ALG-Int
  • 8/6/2019 C Articles

    10/54

    Subject: C++

    Beginner books

    Programming: Principles and Practice Using C++

    by Bjarne Stroustrup

    An Introduction to Programming by the Inventor of C++

    Preparation for Programming in the Real World

    The book assumes that you aim eventually to write non-trivial programs, whether for

    work in software development or in some other technical field.

    Focus on Fundamental Concepts and Techniques

    The book explains fundamental concepts and techniques in greater depth than traditional

    introductions. This approach will give you a solid foundation for writing useful, correct,

    maintainable, and efficient code.

    Programming with Todays C++

    The book is an introduction to programming in general, including object-oriented

    programming and generic programming. It is also a solid introduction to the C++

    programming language, one of the most widely used languages for real-world software.

    The book presents modern C++ programming techniques from the start, introducing the

    C++ standard library to simplify programming tasks.

    10

  • 8/6/2019 C Articles

    11/54

    For BeginnersAnd Anyone Who Wants to Learn Something New

    The book is primarily designed for people who have never programmed before, and ithas been tested with more than 1,000 first-year university students. However,

    practitioners and advanced students will gain new insight and guidance by seeing how a

    recognized master approaches the elements of his art.

    Provides a Broad View

    The first half of the book covers a wide range of essential concepts, design and

    programming techniques, language features, and libraries. Those will enable you to write

    programs involving input, output, computation, and simple graphics. The second half

    explores more specialized topics, such as text processing and testing, and provides

    abundant reference material. Source code and support supplements are available from the

    authors website.

    Intermediate and expert books

    The C++ Programming Language: Third Edition

    by Bjarne Stroustrup

    Written by the inventor of the language, the book is the defining, classic text on the

    language that has become central to software development over the past five years. This

    third edition incorporates additions and changes on a major scale. In particular, the new

    edition is based on the ANSI/ISO C++ final draft with its many new language features -

    templates, exceptions, namespaces, and run-time type identification, to name a few - in

    addition to the C++ Standard Template Library that has revolutionized C++

    development.

    11

  • 8/6/2019 C Articles

    12/54

    Throughout, the book does far more than merely describe every element of the language.

    The focus is on showing how the language is used as a tool for design and programming,

    and teaching the basic concepts programmers need to master C++. With this thirdedition, Stroustrup has made the book even more accessible to those new to the language

    while adding information and techniques that even expert C++ programmers will find

    invaluable.

    Exceptional C++

    by Herb Sutter

    Aimed at the experienced C++ programmer, Herb Sutter's ExceptionalC++ tests any

    reader's knowledge of advanced C++ language features and idioms with several dozen

    programming puzzles and explanations. This is a book that can definitely help bring your

    C++ class design skills to the next level.

    Based on the author's Guru of the Week Internet column, this book poses a series of

    challenging questions on the inner workings of C++, centring around generic

    programming with the Standard Template Library(STL), exception handling, memory

    management and class design. Even if you think you know C++ well, most of these

    problems will teach you something more about the language and how to write more

    robust classes that are "exception safe". Don't think this is just "language lawyering"

    though. The author's explanations stress sound programming principles (favouring

    simplicity) and idioms (such as the Pimpl idiom for class design that promotes faster

    compile times and better maintainability, or using "smart" auto_ptr's with STL.) Judging

    from the range and depth of these examples, Sutter's command of the inner workings of

    C++ is impressive and he does an excellent job at conveying this expertise without

    jargon or a lot of theory.

    12

  • 8/6/2019 C Articles

    13/54

    After reading this book, C++ designers will learn several "best practices" at how to write

    robust, efficient classes that are "exception safe" (meaning they don't throw any handled

    exceptions and don't leak resources). Chances are you'll gain a better understanding of

    memory management techniques and working with STL too. For the experienceddeveloper seeking leading-edge knowledge of some of the best ways to use C++,

    ExceptionalC++ is both a challenging and truly worthwhile source of information.

    --Richard Dragan, Amazon.com

    More Exceptional C++: 40 More Engineering Puzzles, Programming Problems, and

    Solutions

    By Herb Sutter

    More Exceptional C++ continues where Herb Sutter's best-selling Exceptional C++ left

    off, delivering 40 puzzles that illuminate the most challenging -- and most powerful --

    aspects of C++. More Exceptional C++ offers many new puzzles focused on generic

    programming and the C++ Standard Template Library, including important techniques

    such as traits and predicates, as well as key considerations in using standard containers

    and algorithms -- many of them never covered elsewhere. More Exceptional C++

    contains a detailed new section (and two appendices) on optimization in single- and

    multithreaded environments. It also provides important new insights on crucial topics

    first introduced in Exceptional C++, including exception safety, generic programming,

    and memory management. For all C++ programmers.

    Exceptional C++ Style: 40 New Engineering Puzzles, Programming Problems and

    Solutions by Herb Sutter

    Software "style" is about finding the perfect balance between overhead and

    functionality... elegance and maintainability... flexibility and excess. In Exceptional C++

    Style, legendary C++ guru Herb Sutter presents 40 new programming scenarios designed

    13

  • 8/6/2019 C Articles

    14/54

    to analyze not only the what but the why and help you find just the right balance in your

    software.

    Organized around practical problems and solutions, this book offers new insight intocrucial C++ details and interrelationships, and new strategies for today's key C++

    programming techniques--including generic programming, STL, exception safety, and

    more. You'll find answers to questions like:

    What can you learn about library design from the STL itself?

    How do you avoid making templated code needlessly non-generic?

    Why shouldn't you specialize function templates? What should you do instead?

    How does exception safety go beyond try and catch statements?

    Should you use exception specifications, or not?

    When and how should you "leak" the private parts of a class?

    How do you make classes safer for versioning?

    What's the real memory cost of using standard containers?

    How can using const really optimize your code?

    How does writing inline affect performance? When does code that looks wrong actually compile and run perfectly, and why

    should you care?

    What's wrong with the design of std::string?

    Exceptional C++ Style will help you design, architect, and code with style--and achieve

    greater robustness and performance in all your C++ software.

    C++ Coding Standards: Rules, Guidelines, and Best Practices by Herb Sutter

    Consistent, high-quality coding standards improve software quality, reduce time-to-

    market, promote teamwork, eliminate time wasted on inconsequential matters, and

    simplify maintenance. Now, two of the world's most respected C++ experts distill the

    14

  • 8/6/2019 C Articles

    15/54

    rich collective experience of the global C++ community into a set of coding standards

    that every developer and development team can understand and use as a basis for their

    own coding standards.

    The authors cover virtually every facet of C++ programming: design and coding style,

    functions, operators, class design, inheritance, construction/destruction, copying,

    assignment, namespaces, modules, templates, generality, exceptions, STL containers and

    algorithms, and more. Each standard is described concisely, with practical examples.

    From type definition to error handling, this book presents C++ best practices, including

    some that have only recently been identified and standardized-techniques you may not

    know even if you've used C++ for years. Along the way, you'll find answers to questions

    like

    What's worth standardizing--and what isn't?

    What are the best ways to code for scalability?

    What are the elements of a rational error handling policy?

    How (and why) do you avoid unnecessary initialization, cyclic, and definitional

    dependencies? When (and how) should you use static and dynamic polymorphism together?

    How do you practice "safe" overriding?

    When should you provide a no-fail swap?

    Why and how should you prevent exceptions from propagating across module

    boundaries?

    Why shouldn't you write namespace declarations or directives in a header file?

    Why should you use STL vector and string instead of arrays?

    How do you choose the right STL search or sort algorithm?

    What rules should you follow to ensure type-safe code?

    15

  • 8/6/2019 C Articles

    16/54

    Whether you're working alone or with others, C++ Coding Standards will help you write

    cleaner code--and write it faster, with fewer hassles and less frustration.

    C++ in a Nutshell: A Language & Library Referenceby Ray Lischner

    C++ is a powerful, highly flexible, and adaptable programming language that allows

    software engineers to organize and process information quickly and effectively. This is a

    complete reference to C++ which is organized first by topic, then followed by an

    alphabetical reference to the language's keywords, complete with syntax summaries and

    pointers to the topic references. The library reference is organized by header file, and

    each library chapter and class declaration presents the classes and types in alphabetical

    order, for easy lookup. Cross-references link related methods, classes, and other key

    features. This resource should be useful for students as well as professional

    programmers. When you're programming, you need answers to questions about language

    syntax or parameters required by library routines quickly. What, for example, is the C++

    syntax to define an alias for a namespace? Just how do you create and use an iterator to

    work with the contents of a standard library container? This book is a concise desktop

    reference that answers these questions, putting the full power of this flexible, adaptable

    (but somewhat difficult to master) language at every C++ programmer's fingertips.

    The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis

    The C++ Standard Library provides a set of common classes and interfaces that greatly

    extend the core C++ language. Josuttis' book not only provides comprehensive

    documentation of each library component, it also offers clearly written explanations of

    complex concepts, describes the practical programming details needed for effective use,

    and gives example after example of working code. This thoroughly up-to-date book

    reflects the newest elements of the C++ standard library incorporated into the full

    ANSI/ISO C++ language standard. In particular, the text focuses on the Standard

    16

  • 8/6/2019 C Articles

    17/54

    Template Library (STL), examining containers, iterators, function objects, and STL

    algorithms.

    C++ Templates: The Complete Guideby David Vandevoorde, Nicolai M. Josuttis

    Templates are among the most powerful features of C++, but they are too often

    neglected, misunderstood, and misused. C++ Templates: The Complete Guide provides

    software architects and engineers with a clear understanding of why, when, and how to

    use templates to build and maintain cleaner, faster, and smarter software more

    efficiently.

    C++ Templates begins with an insightful tutorial on basic concepts and language

    features. The remainder of the book serves as a comprehensive reference, focusing first

    on language details, then on a wide range of coding techniques, and finally on advanced

    applications for templates. Examples used throughout the book illustrate abstract

    concepts and demonstrate best practices.

    Readers learn

    The exact behaviors of templates

    How to avoid the pitfalls associated with templates

    Idioms and techniques, from the basic to the previously undocumented

    How to reuse source code without threatening performance or safety

    How to increase the efficiency of C++ programs

    How to produce more flexible and maintainable software

    This practical guide shows programmers how to exploit the full power of the

    template features in C++.

    17

  • 8/6/2019 C Articles

    18/54

    The companion Web site at http://www.josuttis.com/tmplbook/ contains sample code and

    additional updates.

    Subject: Algorithms and Data Structures

    Beginner books

    Introduction to Algorithms

    by TH Cormen

    This title covers a broad range of algorithms in depth, yet makes their design andanalysis accessible to all levels of readers. Each chapter is relatively self-contained and

    can be used as a unit of study. The algorithms are described in English and in a

    pseudocode designed to be readable by anyone who has done a little programming. The

    explanations have been kept elementary without sacrificing depth of coverage or

    mathematical rigor. This second edition features new chapters on the role of algorithms,

    probabilistic analysis and randomized algorithms, and linear programming, as well as

    extensive revisions to virtually every section of the book. In a subtle but important

    change, loop invariants are introduced early and used throughout the text to prove

    algorithm correctness. Without changing the mathematical and analytic focus, the

    authors have moved much of the mathematical foundations material from Part I to an

    appendix and have included additional motivational material at the beginning.

    Intermediate and expert books

    The Art of Computer Programming

    by Donald E. Knuth

    18

  • 8/6/2019 C Articles

    19/54

    This multivolume work is widely recognized as the definitive description of classical

    computer science. The first three volumes have for decades been an invaluable resource

    in programming theory and practice for students, researchers, and practitioners alike.

    The bible of all fundamental algorithms and the work that taught many of today's

    software developers most of what they know about computer programming. --Byte,

    September 1995

    Countless readers have spoken about the profound personal influence of Knuth's work.

    Scientists have marveled at the beauty and elegance of his analysis, while ordinary

    programmers have successfully applied his "cookbook" solutions to their day-to-day

    problems. All have admired Knuth for the breadth, clarity, accuracy, and good humor

    found in his books.

    I can't begin to tell you how many pleasurable hours of study and recreation they have

    afforded me! I have pored over them in cars, restaurants, at work, at home! and even at a

    Little League game when my son wasn't in the line-up. --Charles Long

    Primarily written as a reference, some people have nevertheless found it possible and

    interesting to read each volume from beginning to end.A programmer in China even

    compared the experience to reading a poem.

    If you think you're a really good programmer! read [Knuth's] Art of Computer

    Programming! You should definitely send me a resume if you can read the whole thing.

    --Bill Gates

    19

  • 8/6/2019 C Articles

    20/54

    Whatever your background, if you need to do any serious computer programming, you

    will find your own good reason to make each volume in this series a readily accessible

    part of your scholarly or professional library.

    It's always a pleasure when a problem is hard enough that you have to get the Knuths off

    the shelf. I find that merely opening one has a very useful terrorizing effect on

    computers. --Jonathan Laventhol

    For the first time in more than 20 years, Knuth has revised all three books to reflect more

    recent developments in the field. His revisions focus specifically on those areas where

    knowledge has converged since publication of the last editions, on problems that have

    been solved, on problems that have changed. In keeping with the authoritative character

    of these books, all historical information about previous work in the field has been

    updated where necessary. Consistent with the author's reputation for painstakingperfection, the rare technical errors in his work, discovered by perceptive and demanding

    readers, have all been corrected. Hundreds of new exercises have been added to raise

    new challenges.

    Copy constructors, assignment operators, and exception safe

    assignment

    Published byjsmith

    Last update on Aug 20, 2010 at 7:42am UTC

    What is a copy constructor?

    20

    http://cplusplus.com/member/jsmith/http://cplusplus.com/member/jsmith/
  • 8/6/2019 C Articles

    21/54

    A copy constructor is a special constructor for a class/struct that is used to make a copy

    of an existing instance. According to the C++ standard, the copy constructor for MyClass

    must have one of the following signatures:

    1

    2

    3

    4

    MyClass( const MyClass& other );

    MyClass( MyClass& other );

    MyClass( volatileconst MyClass& other );

    MyClass( volatile MyClass& other );

    Note that none of the following constructors, despite the fact that they coulddo the same

    thing as a copy constructor, are copy constructors:

    1

    2

    MyClass( MyClass* other );

    MyClass( const MyClass* other );

    or my personal favorite way to create an infinite loop in C++:

    MyClass( MyClass other );

    21

  • 8/6/2019 C Articles

    22/54

    When do I need to write a copy constructor?

    First, you should understand that if you do not declare a copy constructor, thecompiler gives you one implicitly. The implicit copy constructor does a

    member-wise copy of the source object.

    For example, given the class:

    1

    2

    34

    5

    class MyClass {

    int x;

    charc;std::string s;

    };

    the compiler-provided copy constructor is exactly equivalent to:

    1

    2

    3

    MyClass::MyClass( const MyClass& other ) :

    x( other.x ), c( other.c ), s( other.s )

    {}

    In many cases, this is sufficient. However, there are certain circumstances where the

    member-wise copy version is not good enough. By far, the most common reason the

    default copy constructor is not sufficient is because the object contains raw pointers and

    you need to take a "deep" copy of the pointer. That is, you don't want to copy the pointer

    itself; rather you want to copy what the pointerpoints to. Why do you need to take

    "deep" copies? This is typically because the instance owns the pointer; that is, the

    22

  • 8/6/2019 C Articles

    23/54

    instance is responsible for calling delete on the pointer at some point (probably the

    destructor). If two objects end up calling delete on the same non-NULL pointer, heap

    corruption results.

    Rarely you will come across a class that does not contain raw pointers yet the default

    copy constructor is not sufficient.

    An example of this is when you have a reference-counted object. boost::shared_ptr is

    example.

    Const correctness

    When passing parameters by reference to functions or constructors, be very careful about

    const correctness. Pass by non-const reference ONLY if the function will modify the

    parameter and it is the intent to change the caller's copy of the data, otherwise pass by

    const reference.

    Why is this so important? There is a small clause in the C++ standard that says that non-

    const references cannot bind to temporary objects.

    A temporary object is an instance of an object that does not have a variable name. For

    example:

    std::string( "Hello world" );

    is a temporary, because we have not given it a variable name. This is not a temporary:

    23

  • 8/6/2019 C Articles

    24/54

    std::string s( "Hello world" );

    because the object's name is s.

    What is the practical implication of all this? Consider the following:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    1617

    18

    19

    20

    // Improperly declared function: parameter should be const reference:

    void print_me_bad( std::string& s ) {

    std::cout

  • 8/6/2019 C Articles

    25/54

    Many of the STL containers and algorithms require that an object be copyable.

    Typically, this means that you need to have the copy constructor that takes a const

    reference, for the above reasons.

    What is an assignment operator?

    The assignment operator for a class is what allows you to use = to assign one instance to

    another. For example:

    1

    2

    MyClass c1, c2;

    c1 = c2; // assigns c2 to c1

    There are actually several different signatures that an assignment operator can have:

    (1) MyClass& operator=( const MyClass& rhs );

    (2) MyClass& operator=( MyClass& rhs );

    (3) MyClass& operator=( MyClass rhs );

    (4) const MyClass& operator=( const MyClass& rhs );

    (5) const MyClass& operator=( MyClass& rhs );

    (6) const MyClass& operator=( MyClass rhs );

    (7) MyClass operator=( const MyClass& rhs );

    25

  • 8/6/2019 C Articles

    26/54

    (8) MyClass operator=( MyClass& rhs );

    (9) MyClass operator=( MyClass rhs );

    These signatures permute both the return type and the parameter type. While the return

    type may not be too important, choice of the parameter type is critical.

    (2), (5), and (8) pass the right-hand side by non-const reference, and is not

    recommended. The problem with these signatures is that the following code would not

    compile:

    1

    2

    MyClass c1;

    c1 = MyClass( 5, 'a', "Hello World" ); // assuming this constructor exists

    This is because the right-hand side of this assignment expression is a temporary (un-

    named) object, and the C++ standard forbids the compiler to pass a temporary object

    through a non-const reference parameter.

    This leaves us with passing the right-hand side either by value or by const reference.

    Although it would seem that passing by const reference is more efficient than passing by

    value, we will see later that for reasons of exception safety, making a temporary copy of

    the source object is unavoidable, and therefore passing by value allows us to write fewer

    lines of code.

    When do I need to write an assignment operator?

    26

  • 8/6/2019 C Articles

    27/54

    First, you should understand that if you do not declare an assignment operator, the

    compiler gives you one implicitly. The implicit assignment operator does member-wise

    assignment of each data member from the source object. For example, using the class

    above, the compiler-provided assignment operator is exactly equivalent to:

    1

    2

    3

    4

    5

    6

    MyClass& MyClass::operator=( const MyClass& rhs ) {

    x = other.x;

    c = other.c;

    s = other.s;

    return *this;

    }

    In general, any time you need to write your own custom copy constructor, you also need

    to write a custom assignment operator.

    What is meant by Exception Safe code?

    A little interlude to talk about exception safety, because programmers often

    misunderstand exception handling to be exception safety.

    A function which modifies some "global" state (for example, a reference parameter, or a

    member function that modifies the data members of its instance) is said to be exception

    safe if it leaves the global state well-defined in the event of an exception that is thrown at

    any point during the function.

    27

  • 8/6/2019 C Articles

    28/54

    What does this really mean? Well, let's take a rather contrived (and trite) example. This

    class wraps an array of some user-specified type. It has two data members: a pointer to

    the array and a number of elements in the array.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    template< typename T >

    class MyArray {

    size_t numElements;

    T* pElements;

    public:

    size_t count() const { return numElements; }

    MyArray& operator=( const MyArray& rhs );

    };

    Now, assignment of one MyArray to another is easy, right?

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    template

    MyArray::operator=( const MyArray& rhs ) {

    if( this != &rhs ) {

    delete [] pElements;

    pElements = new T[ rhs.numElements ];

    for( size_t i = 0; i < rhs.numElements; ++i )

    pElements[ i ] = rhs.pElements[ i ];

    numElements = rhs.numElements;

    }

    return *this;

    }

    28

  • 8/6/2019 C Articles

    29/54

    Well, not so fast. The problem is, the line

    pElements[ i ] = rhs.pElements[ i ];

    could throw an exception. This line invokes operator= for type T, which could be some

    user-defined type whose assignment operator might throw an exception, perhaps an out-

    of-memory (std::bad_alloc) exception or some other exception that the programmer of

    the user-defined type created.

    What would happen if it did throw, say on copying the 3rd element of 10 total? Well, the

    stack is unwound until an appropriate handler is found. Meanwhile, what is the state of

    our object? Well, we've reallocated our array to hold 10 T's, but we've copied only 2 of

    them successfully. The third one failed midway, and the remaining seven were never

    even attempted to be copied. Furthermore, we haven't even changed numElements, so

    whatever it held before, it still holds. Clearly this instance will lie about the number of

    elements it contains if we call count() at this point.

    But clearly it was never the intent of MyArray's programmer to have count() give a

    wrong answer. Worse yet, there could be other member functions that rely more heavily

    (even to the point of crashing) on numElements being correct. Yikes -- this instance is

    clearly a timebomb waiting to go off.

    29

  • 8/6/2019 C Articles

    30/54

    This implementation of operator= is not exception safe: if an exception is thrown during

    execution of the function, there is no telling what the state of the object is; we can only

    assume that it is in such a bad state (ie, it violates some of its own invariants) as to be

    unusable. If the object is in a bad state, it might not even be possible to destroy the objectwithout crashing the program or causing MyArray to perhaps throw another exception.

    And we know that the compiler runs destructors while unwinding the stack to search for

    a handler. If an exception is thrown while unwinding the stack, the program necessarily

    and unstoppably terminates.

    How do I write an exception safe assignment operator?

    The recommended way to write an exception safe assignment operator is via the copy-

    swap idiom. What is the copy-swap idiom? Simply put, it is a two- step algorithm: first

    make a copy, then swap with the copy. Here is our exception safe version of operator=:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    template

    MyArray::operator=( const MyArray& rhs ) {

    // First, make a copy of the right-hand side

    MyArray tmp( rhs );

    // Now, swap the data members with the temporary:

    std::swap( numElements, tmp.numElements );

    std::swap( pElements, tmp.pElements );

    return *this;

    }

    30

  • 8/6/2019 C Articles

    31/54

    Here's where the difference between exception handling and exception safety is

    important: we haven'tpreventedan exception from occurring; indeed, the copy

    construction of tmp from rhs may throw since it will copy T's. But, if the copy

    construction does throw, notice how the state of *this has not changed, meaning that in

    the face of an exception, we can guarantee that *this is still coherent, and furthermore,

    we can even say that it is left unchanged.

    But, you say, what about std::swap? Could it not throw? Yes and no. The default

    std::swap, defined in can throw, since std::swap looks like this:

    1

    2

    3

    4

    5

    6

    7

    template< typename T >

    swap( T& one, T& two )

    {

    T tmp( one );

    one = two;

    two = tmp;

    }

    The first line runs the copy constructor of T, which can throw; the remaining lines are

    assignment operators which can also throw.

    HOWEVER, if you have a type T for which the default std::swap() may result in either

    T's copy constructor or assignment operator throwing, you are politely required to

    provide a swap() overload for your type that does not throw. [Since swap() cannot return

    31

  • 8/6/2019 C Articles

    32/54

    failure, and you are not allowed to throw, your swap() overload must always succeed.]

    By requiring that swap does not throw, the above operator= is thus exception safe: either

    the object is completely copied successfully, or the left-hand side is left unchanged.

    Now you'll notice that our implementation of operator= makes a temporary copy as its

    first line of code. Since we have to make a copy, we might as well let the compiler do

    that for us automatically, so we can change the signature of the function to take the right-

    hand side by value (ie, a copy) rather than by reference, and this allows us to eliminate

    one line of code:

    1

    2

    3

    4

    5

    6

    template

    MyArray::operator=( MyArray tmp ) {

    std::swap( numElements, tmp.numElements );

    std::swap( pElements, tmp.pElements );

    return *this;

    }

    How to use tags

    Published by firedraco

    Last update on Aug 10, 2010 at 10:25pm UTC

    This article will show you the common types of tags and how to use them.

    1.) Source Code Tags

    Syntax:

    [code]int main() { return 0; }[/code]

    Becomes:

    1 int main() {

    32

    http://cplusplus.com/member/firedraco/http://cplusplus.com/member/firedraco/
  • 8/6/2019 C Articles

    33/54

    2

    3

    return 0;

    }

    Use this whenever you post code, as it provides coloring most people are used to, as well

    as preserving indentation (a Good Thing).

    You can also make it start at a specific line number (10, in this example) by doing this:

    [code firstline=10]//start in the middle of some function

    for(unsigned int i = 0; i < 5; ++i) {

    do_something(i);

    }[/code]

    This becomes:

    10

    11

    12

    13

    //start in the middle of some function

    for(unsignedint i = 0; i < 5; ++i) {

    do_something(i);

    }

    One warning however, long code lines will simply stretch the box, so try to avoid using

    overly long lines of code.

    2.) Output Tags

    Syntax:

    [output]Code Output Goes Here

    1234567890[/output]

    Becomes:

    33

  • 8/6/2019 C Articles

    34/54

    Code Output Goes Here

    1234567890

    Use this if you have output that you want to display from your code, e.g.: expected

    results, actual results.

    1/2.) Combining the Above

    If you have a short piece of code and output you wish to display, you can use the

    following format:

    [code]int main() {

    std::cout

  • 8/6/2019 C Articles

    35/54

    [quote=Somebody]I didn't say that!![/quote]

    Becomes:

    Quote goes here.or

    Somebody wrote:

    I didn't say that!!

    Use this to quote other people or stuff from another site. This makes it more obvious as

    to what exactly was said.

    4.) Teletype Tags

    Syntax:

    [tt]abcdefghij 1234567890[/tt]

    Becomes: abcdefghij 1234567890

    This tag is quite similar to the Code Output tag, shown above, except it does not have a

    box surrounding it, and will delete excess whitespace at the beginning of a line.

    5.) Miscellaneous Tags

    This section contains the tags that simply alter the appearance of the text.

    Bold: [b]Text[/b] Text

    Italic: [i]Text[/i] Text

    Underline:

    [u]Text[/u] Text Small:

    35

  • 8/6/2019 C Articles

    36/54

    [small]Text[/small] Text

    Subscript:

    [sub]Text[/sub] Text

    Superscript:

    [sup]Text[/sup] Text

    6.) More Information

    When using the "Tags:" selector on the right side of the post area, select the information

    you want to quote, italicize, etc, and then click on the respective button. This causes thetags to surround the selected text, rather then simply be added at the end of your post.

    Converting numbers to strings and strings to numbers

    Published by Bazzy

    Last update on Aug 22, 2010 at 11:42am UTC

    Converting numbers to text and vice versa is a common issue as it can be useful in many

    different situations and C++ doesn't provide a tool designed specifically to solve this

    problem.

    Luckily C++ is a general purpose language so it allows to solve this quite easily and, as

    most things, you have many ways of accomplishing this task.

    Here are listed some

    Contents:

    C++ - stringstreams

    o Number to String

    Custom Formatting

    36

    http://cplusplus.com/member/Bazzy/http://cplusplus.com/articles/numb_to_text/#sshttp://cplusplus.com/articles/numb_to_text/#n2shttp://cplusplus.com/articles/numb_to_text/#cfhttp://cplusplus.com/member/Bazzy/http://cplusplus.com/articles/numb_to_text/#sshttp://cplusplus.com/articles/numb_to_text/#n2shttp://cplusplus.com/articles/numb_to_text/#cf
  • 8/6/2019 C Articles

    37/54

    o String to Number

    o Simple Sample Functions

    C++ - boost library

    C - stdio C - stdlib

    Writing your own function

    C++ - stringstreams

    The C++ stream library is powerful and it allows easy formatted input output operations.

    With stringstreams you can perform this input/output to string, this allows you to convert

    numbers ( or any type with the > stream operators overloaded ) to and from strings.With stringstreams you can use the same syntax to convert the different numeric types.

    To use stringstreams you need to #include

    Number to String

    Converting a number to a string takes two steps using stringstreams:

    1. Outputting the value of the number to the stream

    2. Getting the string with the contents of the stream

    As with this conversion needs only output operation with the stream,

    an ostringstream ( output string stream ) can be used instead of the stream for both input

    and output ( stringstream )

    Here is an example which shows each step:

    1

    2

    3

    4

    int Number = 123; // number to be converted to a string

    string Result; // string which will contain the result

    37

    http://cplusplus.com/articles/numb_to_text/#s2nhttp://cplusplus.com/articles/numb_to_text/#eghttp://cplusplus.com/articles/numb_to_text/#boosthttp://cplusplus.com/articles/numb_to_text/#stdiohttp://cplusplus.com/articles/numb_to_text/#stdlibhttp://cplusplus.com/articles/numb_to_text/#badhttp://www.cplusplus.com/reference/iostream/http://www.cplusplus.com/reference/iostream/stringstream/http://cplusplus.com/articles/numb_to_text/#s2nhttp://cplusplus.com/articles/numb_to_text/#eghttp://cplusplus.com/articles/numb_to_text/#boosthttp://cplusplus.com/articles/numb_to_text/#stdiohttp://cplusplus.com/articles/numb_to_text/#stdlibhttp://cplusplus.com/articles/numb_to_text/#badhttp://www.cplusplus.com/reference/iostream/http://www.cplusplus.com/reference/iostream/stringstream/
  • 8/6/2019 C Articles

    38/54

    5

    6

    7

    89

    10

    11

    ostringstream convert; // stream used for the conversion

    convert

  • 8/6/2019 C Articles

    39/54

    2

    3

    4

    56

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    #include

    #include

    #include

    #include // this should be already included in

    // Defining own numeric facet:

    class WithComma:public numpunct // class for decimal numbers using comma

    instead of point

    {

    protected:

    chardo_decimal_point() const { return','; } // change the decimal separator

    };

    // Conversion code:

    double Number = 0.12; // Number to convert to string

    ostringstream Convert;

    locale MyLocale( locale(), new WithComma);// Crate customized locale

    Convert.imbue(MyLocale); // Imbue the custom locale to the stringstream

    Convert

  • 8/6/2019 C Articles

    40/54

    31

    32

    33

    String to Number

    Also converting a string to a number via stringstream takes two steps:

    1. Constructing the stream from the string

    2. Reading the value into the variable

    For this ( as you need to read input from the stream ) an istringstream will be used

    While a number can always be converted in a string, a string must be valid to be

    converted to a number ( eg: An attempt of converting "hello" to an integer would

    certainly fail ) so on this conversion, some checking must be done

    Here is the code example:1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    string Text = "456"; // string containing the number

    int Result; //number which will contain the result

    istringstream convert(Text); // stringstream used for the conversion constructed with

    the contents of 'Text'

    // ie: the stream will start containing the characters of 'Text'

    if( !(convert >> Result) ) //give the value to 'Result' using the characters in the stream

    Result = 0; //if that fails set 'Result' to 0

    //'Result' now equal to 456

    40

  • 8/6/2019 C Articles

    41/54

    This conversion is even easier to reduce to a single line:

    1

    23

    string Text = "456";

    int Number;if( ! (istringstream(Text) >> Number) ) Number = 0;

    In the above code an object of istringstream gets constructed from

    'Text' istringstream(Text) and its contents get read into the numeric variable >> Number.

    If that operation fails if( !, 'Number' is set to zero Number = 0;

    Locales and manipulators can be used as well as with any stream

    More complex cases

    A generic stringstream ( which could be used both for input and for output ) can be

    useful in some more complex situations and in almost any situation you need to performoperations not provided by string

    Simple Sample Functions

    Here are listed some functions to perform these conversion using stringstreams:

    1

    2

    3

    4

    template

    string NumberToString ( T Number )

    {

    ostringstream ss;

    41

  • 8/6/2019 C Articles

    42/54

    5

    6

    7

    ss > result ? result : 0;

    }

    Usage: StringToNumber ( String );

    Notice: In the code examples std:: was omitted to make the code simpler

    Using the last functions, there is no way of detecting whether the conversion

    succeded or failed

    C++ - Boost Library

    Using stringstreams is the standard C++ way of doing these conversions but they usually

    need a few lines of code Among the Boost libraries there is lexical_cast which allows to

    perform the stringstream conversions through simple function call To make this library

    working, just include the header, it doesn't need to be linked

    1

    2

    3

    // Boost header needed:

    #include

    42

    http://www.boost.org/http://www.boost.org/doc/libs/1_40_0/libs/conversion/lexical_cast.htm#lexical_casthttp://www.boost.org/http://www.boost.org/doc/libs/1_40_0/libs/conversion/lexical_cast.htm#lexical_cast
  • 8/6/2019 C Articles

    43/54

    4

    5

    6

    78

    // Number to string conversion:

    Text = boost::lexical_cast(Number);

    // String to number conversion:

    Number = boost::lexical_cast(Text);

    The above examples don't handle eventual conversion failures

    When boost::lexical_cast fails, it throws boost::bad_lexical_cast ( derived

    from std::bad_cast )

    1

    23

    4

    5

    6

    7

    8

    9

    10

    11

    try

    {Number = boost::lexical_cast(Text);

    }

    catch ( const boost::bad_lexical_cast &exc ) // conversion failed, exception thrown by

    lexical_cast and caught

    {

    Number = 0; // give 'Number' an arbitrary value ( in this case zero )

    // if you don't give it any value, it would maintain the value it had before the

    conversion

    // A string containing a description of the exception can be found in exc.what()

    }

    C - stdio

    Number to String

    In C there is no stream library, but the function sprintfcan be used for conversion

    It works in a similar way toprintfbut it will put the characters in a C string ( a character

    array ) instead of stdout

    43

    http://www.cplusplus.com/reference/std/typeinfo/bad_cast/http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/http://www.cplusplus.com/reference/clibrary/cstdio/printf/http://www.cplusplus.com/reference/std/typeinfo/bad_cast/http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/http://www.cplusplus.com/reference/clibrary/cstdio/printf/
  • 8/6/2019 C Articles

    44/54

    Using this is not as easy as with streams as the format string changes depending on the

    type of the number which needs to be converted

    Example:1

    2

    3

    4

    5

    int Number = 123; // number to convert

    charResult[16]; // string which will contain the number

    sprintf ( Result, "%d", Number ); // %d makes the result be a decimal integer

    String to Number

    As printf, also scanfhas a related function which can read from a character array, sscanf

    1

    2

    3

    4

    5

    charText[] = "456"; // string to be converted

    int Result; // number which will contain the result

    sscanf ( Text, "%d", &Result );

    If sscanf fails ( ie: the string is not a number ), the value of the variable passed remains

    unchanged, in that case the function should return zero as no argument were read

    successfully, if the string passed is so bad that nothing can be read from it, it would

    return EOF:

    1

    2

    3

    4

    5

    charText[] = "456"; // string to be converted

    int Result; // number which will contain the result

    int Succeeded = sscanf ( Text, "%d", &Result );

    44

    http://www.cplusplus.com/reference/clibrary/cstdio/scanf/http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/http://www.cplusplus.com/reference/clibrary/cstdio/EOF/http://www.cplusplus.com/reference/clibrary/cstdio/scanf/http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/http://www.cplusplus.com/reference/clibrary/cstdio/EOF/
  • 8/6/2019 C Articles

    45/54

    6

    7

    8

    if ( !Succeeded || Succeeded == EOF ) // check if something went wrong during the

    conversion

    Result = 0;

    C stdlib

    The stdlibheader contains some functions to convert text and numbers

    Notice that some of these functions are not standard!

    These functions are:

    itoa

    atoi

    atol

    atof

    strtol

    strtoul

    strtod

    - For examples refer to the individual reference pages -

    Writing your own function

    Using already existing libraries is easier and better but, just to show how some of the

    above solutions work, here are some examples of how to write functions to convert text

    to numbers and numbers to text using only the core language, the following examples are

    from the book "The C Programming Language"

    Here is itoa ( Integer TO Alphabet )

    45

    http://www.cplusplus.com/reference/clibrary/cstdlib/http://www.cplusplus.com/reference/clibrary/cstdlib/http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/atoi.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/atol.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/atof.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/strtol.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/strtoul.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/strtod.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/atoi.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/atol.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/atof.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/strtol.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/strtoul.htmlhttp://www.cplusplus.com/reference/clibrary/cstdlib/strtod.html
  • 8/6/2019 C Articles

    46/54

    1

    2

    3

    45

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    /* itoa: convert n to characters in s */

    void itoa(int n, chars[])

    {

    int i, sign;

    if((sign = n) < 0) /* record sign */

    n = -n; /* make n positive */

    i = 0;

    do { /* generate digits in reverse order */

    s[i++] = n % 10 + '0'; /* get next digit */

    } while ((n /= 10) > 0); /* delete it */ if(sign < 0)

    s[i++] = '-';

    s[i] = '\0';

    reverse(s);

    }

    Here is the function reverse used in itoa:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    /* reverse: reverse string s in place */

    void reverse(chars[])

    {

    int i, j;

    charc;

    for(i = 0, j = strlen(s)-1; i

  • 8/6/2019 C Articles

    47/54

    12 }

    reverse uses the function strlen from the header cstring ( string.h in C )

    This is easy to implement, here is an example:

    1

    2

    3

    4

    5

    6

    78

    /* strlen: return length of s */

    int strlen(chars[])

    {

    int i = 0;

    while (s[i] != '\0')

    ++i;

    return i;}

    As you can see, is possible to create a ( bad ) conversion function with just some basic C

    The same applies to the opposite conversion:

    1

    2

    34

    5

    6

    7

    8

    9

    /* atoi: convert s to integer */

    int atoi(chars[])

    { int i, n;

    n = 0;

    for(i = 0; s[i] >= '0' && s[i]

  • 8/6/2019 C Articles

    48/54

    How To: Ask Questions The Smart Way

    Published by Grey Wolf

    Last update on Oct 9, 2009 at 11:28am UTC

    Abridged version of the work of Eric Steven Raymond

    Introduction

    In the world of programming, the kind of answers you get to your technical questions

    depends as much on the way you ask the questions as on the difficulty of developing theanswer. The first thing to understand is that programmers actually like hard problems

    and good, thought-provoking questions about them. If we didn't, we wouldn't be here

    Programmers have a reputation for meeting simple questions with what looks like

    hostility or arrogance. It sometimes looks like we're reflexively rude to newbies and the

    ignorant. But this isn't really true.

    Before You Ask

    Before asking a question a, do the following:

    1. Try to find an answer by searching the archives of the forum you plan to post to.

    2. Try to find an answer by searching the Web.

    3. Try to find an answer by reading the manual.

    4. Try to find an answer by reading a FAQ.

    5. Try to find an answer by inspection or experimentation.

    6. Try to find an answer by asking a skilled friend.

    48

    http://cplusplus.com/member/Grey_Wolf/http://cplusplus.com/member/Grey_Wolf/
  • 8/6/2019 C Articles

    49/54

    Prepare your question. Think it through. Hasty-sounding questions get hasty answers or

    none at all.

    When You Ask

    Choose your forum carefully

    Be sensitive in choosing where you ask your question. You are likely to be ignored if

    you:

    post your question to a forum where it's off topic post a very elementary question to a forum where advanced technical questions

    are expected, or vice-versa

    Use meaningful, specific subject headers

    The subject header is your golden opportunity to attract qualified experts' attention. Don't

    waste it on babble like 'Please help me' Don't try to impress us with the depth of your

    anguish; use the space for a super-concise problem description instead.

    More generally, imagine looking at the index of an archive of questions, with just the

    subject lines showing. Make your subject line reflect your question well enough that the

    next guy searching the archive with a question similar to yours will be able to follow the

    thread to an answer rather than posting the question again.

    Write in clear, grammatical, correctly-spelled language

    Expressing your question clearly and well is important. Spend the extra effort to polish

    your language. It doesn't have to be stiff or formal. But it has to be precise.Don't TYPE IN ALL CAPS; this is read as shouting and considered rude.

    If you write like a semi-literate boob you will very likely be ignored. So don't use

    instant-messaging shortcuts.

    49

  • 8/6/2019 C Articles

    50/54

    Be precise and informative about your problem

    Describe the symptoms of your problem carefully and clearly.

    Describe the environment in which it occurs (machine, OS, application,

    whatever).

    Describe the research you did to try and understand the problem before you asked

    the question.

    Describe the diagnostic steps you took to try and pin down the problem yourself

    before you asked the question.

    Do the best you can to anticipate the questions a respondent will ask, and answer them in

    advance in your request for help.

    Volume is not precision

    You need to be precise and informative. This end is not served by simply dumping huge

    volumes of code or data into a help request. If you have a large, complicated test case

    that is breaking a program, try to trim it and make it as small as possible. This is useful

    for at least three reasons. One: being seen to invest effort in simplifying the question

    makes it more likely you'll get an answer, Two: simplifying the question makes it more

    likely you'll get a useful answer. Three: In the process of refining your bug report, you

    may develop a fix or workaround yourself.

    Describe the problem's symptoms, not your guesses

    It's not useful to tell programmers what you think is causing your problem. So, make

    sure you're telling them the raw symptoms of what goes wrong, rather than your

    50

  • 8/6/2019 C Articles

    51/54

    interpretations and theories. Let them do the interpretation and diagnosis. If you feel it's

    important to state your guess, clearly label it as such and describe why that answer isn't

    working for you.

    Describe the goal, not the step

    If you are trying to find out how to do something, begin by describing the goal. Only

    then describe the particular step towards it that you are blocked on. Often, people who

    need technical help have a high-level goal in mind and get stuck on what they think is

    one particular path towards the goal. They come for help with the step, but don't realize

    that the path is wrong. It can take substantial effort to get past this.

    Be explicit about your question

    Open-ended questions tend to be perceived as open-ended time sinks. Those people most

    likely to be able to give you a useful answer are also the busiest people (if only because

    they take on the most work themselves). People like that are allergic to open-ended time

    sinks, thus they tend to be allergic to open-ended questions.

    You are more likely to get a useful response if you are explicit about what you want

    respondents to do (provide pointers, send code,..). This will focus their effort and

    implicitly put an upper bound on the time and energy a respondent must allocate to

    helping you.

    When asking about code

    Don't ask others to debug your broken code without giving a hint what sort of problem

    they should be searching for. Posting a few hundred lines of code, saying "it doesn't

    work", will get you ignored. Posting a dozen lines of code, saying "after line 7 I was

    expecting to see , but occurred instead" is much more likely to get you a

    51

  • 8/6/2019 C Articles

    52/54

    response. If you simply want a code review, say as much up front, and be sure to

    mention what areas you think might particularly need review and why.

    Don't post homework questions

    Programmers are good at spotting homework questions; most of us have done them

    ourselves. Those questions are for you to work out, so that you will learn from the

    experience. It is OK to ask for hints, but not for entire solutions.

    Follow up with a brief note on the solution

    Send a note after the problem has been solved to all who helped you; let them know how

    it came out and thank them again for their help Your followup doesn't have to be long

    and involved; a simple "Howdy ' it was a failed network cable! Thanks, everyone. - Bill"

    would be better than nothing. In fact, a short and sweet summary is better than a long

    dissertation unless the solution has real technical depth. Say what action solved the

    problem, but you need not replay the whole troubleshooting sequence.

    Besides being courteous and informative, this sort of followup will help others searching

    the archive of the mailing-list/newsgroup/forum to know exactly which solution helped

    you and thus may also help them.

    Last, and not least, this sort of followup helps everybody who assisted feel a satisfying

    sense of closure about the problem. Problem narratives that trail off into unresolved

    nothingness are frustrating things; programmers itch to see them resolved. The goodwill

    that scratching that itch earns you will be very, very helpful to you next time you need to

    pose a question.

    How To Interpret Answers

    If you don't understand...

    52

  • 8/6/2019 C Articles

    53/54

    If you don't understand the answer, do not immediately bounce back a demand for

    clarification. Use the same tools that you used to try and answer your original question

    (manuals, FAQs, the Web, skilled friends) to understand the answer. Then, if you still

    need to ask for clarification, exhibit what you have learned.

    If You Can't Get An Answer

    If you can't get an answer, please don't take it personally that we don't feel we can help

    you. Sometimes the members of the asked group may simply not know the answer. No

    response is not the same as being ignored, though admittedly it's hard to spot the

    difference from outside.

    In general, simply re-posting your question is a bad idea. This will be seen as pointlessly

    annoying. Have patience: the person with your answer may be in a different time-zone

    and asleep. Or it may be that your question wasn't well-formed to begin with.

    How To Answer Questions in a Helpful Way

    Be gentle. Problem-related stress can make people seem rude or stupid even when

    they're not.

    Reply to a first offender off-line. There is no need of public humiliation for someone

    who may have made an honest mistake. A real newbie may not know how to search

    archives or where the FAQ is stored or posted.

    If you don't know for sure, say so! A wrong but authoritative-sounding answer is worse

    than none at all. Don't point anyone down a wrong path simply because it's fun to sound

    like an expert. Be humble and honest; set a good example for both the querent and your

    peers.

    If you can't help, don't hinder. Don't make jokes about procedures that could trash the

    user's setup - the poor sap might interpret these as instructions.

    53

  • 8/6/2019 C Articles

    54/54

    Ask probing questions to elicit more details. If you're good at this, the querent will

    learn something - and so might you. Try to turn the bad question into a good one;

    remember we were all newbies once.

    While muttering RTFM is sometimes justified when replying to someone who is just alazy slob, a pointer to documentation (even if it's just a suggestion to google for a key

    phrase) is better.

    If you're going to answer the question at all, give good value. Don't suggest kludgy

    workarounds when somebody is using the wrong tool or approach. Suggest good tools.

    Reframe the question.