562 139 29MB
English Pages [589] Year 2023
Learning C++ MEAP V05 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.
Copyright_2023_Manning_Publications welcome 1_C++_is_brilliant! 2_Exploring_C++_fundamentals 3_Smooth_operator_–exploring_C++_operators_and_conditions 4_Let_it_flow_–_Conditions,_iteration,_and_flow_control 5_Hip_hip_array_–_C++_arrays 6_Vectors_–_your_arrays_"on_steroids" 7_With_strings_attached_-_working_with_string_literals 8_Function_in_action
MEAP Edition Manning Early Access Program Learning C++ Version 5 Copyright 2023 Manning Publications ©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders. https://livebook.manning.com/#!/book/learning-c-plus-plus/discussion
For more information on this and other Manning titles go to manning.com
welcome Thanks for purchasing the MEAP for Learning C++ book. We hope you will enjoy the ride, and with your help, we can perfect the content and flow of each chapter, up to the completed book. We have designed and crafted this book especially for those with no skills in computer programming, or for programmers with some skills in other programming languages, wishing to make the move to C++. C++ is considered to be one of the most powerful and robust programming languages out there, and as such, teaching C++ might be even more challenging than learning it – especially when trying to teach C++ to complete beginners. This book was born from a notion there should be a better way to teach C++, while making sure beginners to the language will not miss out on some of the advanced and fantastic features C++20, which is the new and improved C++ standard, can offer. When we were looking at printed or online guides to some of the new C++20 features, we could clearly see they were not intended for beginners, and even if some were, a true beginner might struggle to understand them. We wanted to change that and offer a true beginner guide to C++20. This book was written using a practical approach, so you can get to know C++ 20, and create practical programs (as opposed to exercises) using your new skills. When writing this book, we did not take anything for granted – we explained the ‘how’ and the ‘why’ as much as possible, and we tried our best to provide our unique perspective and use creative and fun ways, so you can really understand C++, not just know it. We also wanted to write a book which gives readers hands-on advice, tips and tricks, which can be useful when writing real life programs, rather than just “school assignments”. This book was born after each of us approached C++ 20 from a different angle: Michael, having over 30 years of experience in programming in C and
C++, trying to make the most of the C++ 20 new features in commercial products such as a our Anti Malware engine, a new Anti-Virus (which uses our engine), along with other Cyber related products he was working on, and Ruth, with over 25 years of experience in the software industry, who just loves teaching while inventing new teaching methods. We started discussing the need for such book while juggling among complex software projects we were working on as part of our software venture, Secured Globe, Inc. in New York. During that time, the Covid 19 pandemic spread around the world, but the curse turned to be a blessing: lockdown gave us plenty of time to work on our book. Throughout this book, we will be covering basics and advanced features of C++, as well as some basic concepts in computer science and computer programming in general. Obviously we could not cover everything, but we did try to build a solid root foundation for you to continue building your skills upon. By the end of this book, you will be able to write a very practical and complex C++ code as part of the book’s final exercise: a code that can safeguard a computer program from an intellectual property theft by hackers, by turning a code unintelligible. We enjoyed writing this book, and we do hope you will enjoy reading it. We value feedback from our readers and take that feedback very seriously. We will be both looking forward to hearing your feedback, which you are welcome to leave in the comments section in the liveBook Discussion forum. Our book is a dynamic creature which will continue to be finetuned based on readers’ feedback, and hopefully, together with your help, we can craft this book even further, turning it into a true asset for beginners. — Michael Haephrati and Ruth Haephrati about the authors
Michael Haephrati, Co-Founder of Secured Globe, Inc. is an inventor, musician, entrepreneur, and a C++ expert, specializing in software development, vulnerabilities research and Cyber Security. Over the last +30 years, Michael has developed a unique perspective and methodology, combining core technologies, creativity and functionality with the end user experience. Back in 1989, Michael developed Rashumon, the first multilingual graphical word processor for the Amiga. Later, he developed various software products and technologies, especially in the field of Video
Processing, Cyber Security, Data Cleansing, Data Leak Prevention, DRM, and high-end solutions, for government agencies. Recently, he developed the next generation anti-virus and Malware Detection Technology, used by leading tech companies such as Avaxi LLC. Michael also took part in starting a Web3 based Social Ecosystem. Most of his work is developed using C++. Michael regularly writes in Code Project, Microsoft blogs and Pentest Magazine. He is also a music composer and pianist, who likes traveling and long-distance jogging. Ruth Haephrati, Co-Founder of Secured Globe, Inc. is an entrepreneur and a cyber security and cyber intelligence expert with vast computer forensics skills. Ruth started her career back in the early 90s and has since taken part in various projects and emerging technologies, starting with Windows based applications, Web application, Computer vision, IOT, Deep learning and more. During her career, Ruth has designed and developed innovative technologies, including some military grade solutions. She recently also led the R&D of a new and innovative Cryptocurrency marketplace. She is also a painter, photographer and loves jogging. In this book
Copyright 2023 Manning Publications welcome brief contents 1 C++ is brilliant! 2 Exploring C++ fundamentals 3 Smooth operator –exploring C++ operators and conditions 4 Let it flow – Conditions, iteration, and flow control 5 Hip hip array – C++ arrays 6 Vectors – your arrays "on steroids" 7 With strings attached - working with string literals 8 Function in action
1 C++ is brilliant! This chapter covers Learning why C++ is great Considering spoken vs computer languages Discovering the reasons to learn C++ Getting into the correct mindset for programming and C++ in particular Exploring the book’s approach and expectations C++ is alive and kicking and is considered by many to be one of the most powerful and robust programming languages across all platforms. C++ plays a constant key role in evolving technologies of all sorts – from mobile applications, web applications, communication and networking, desktop applications, and up to the most complex and demanding projects, including the human genome project, fundamental physics research at CERN, and the Mars Rover. Everywhere you look, C++ fingerprints are all over it. To use the words of Bjarne Stroustrup, the creator, and designer of C++, " I find it most gratifying that C++ has been used in science: the human genome project, the fundamental physics research at CERN and elsewhere, and the Mars Rovers. It feels great to have contributed, however small". With its versatility and proven track record of success, it's no wonder that C++ remains a vital and essential tool for software developers today, and this book intends to help you start your own journey with C++.
1.1 There’s more to C++ than you can C Despite being considered one of the most complex programming languages, C++ is not only highly sought after, but also extremely rewarding to master. With over 30 years of use and a growing community of more than 5.4 million C++ programmers worldwide[1], it is considered a stable and enduring language that continues to grow in popularity. While there may be easier programming languages available, none of them offer the same level of
robustness, performance, and capabilities simultaneously as C++. This is why C++ remains a valuable tool for developers seeking to create high-quality, reliable software. If you're up for the challenge, learning C++ can be an incredibly rewarding experience that will open up a wealth of career opportunities. One of the unique features of C++ is its ability to handle both low-level and high-level programming tasks. Low-level programming involves working closely with the hardware, using languages that are close to machine code. High-level programming, on the other hand, involves writing code that is more ‘abstract’, simplified, and closer to the natural language we use in everyday communication. C++ can bridge the gap between these two levels of programming, allowing developers to work with both low-level and highlevel elements simultaneously. This versatility makes C++ a popular choice for a wide range of projects, and it is therefore often referred to as a generalpurpose language. Note
The position of several programming languages in relation to the actual hardware is explained and illustrated in Appendix A. With C++ you can craft your code and refine it to the extent of controlling and micro-managing the computer's performance. C++ code can also be written in so many styles and approaches to serve almost any use case. Taking this even further, C++ is like having invented your own programming language: you can create your own commands, style, and code flow, having full control, flexibility, and power in your beautiful coding hands. Good to know
C++ uses 95 keywords. Keywords define one and only one meaning to a used word within your C++ code; for example, the keyword “break” means exiting a specific part of your program and moving to the next, while the keyword “continue” means continuing from a specific part of your program. There are other examples of keywords in C++, such as "if", "else", "while", "for", "return", "class" and many more, (and you will learn and know them all
very soon). These keywords have a specific meaning in the language and are used to perform certain tasks in the program. C uses only 32 keywords, while Python uses 33, and Golang only uses 25.
1.1.1 The peeled onion principal Some say that the freedom C++ offers comes with a price: Complex and flexible programs can be more prone to mistakes and bugs, which can cause your program to crash or behave unexpectedly. This is something to be mindful of when working with C++, especially if you are new to the language. Writing complex code can be a bit like peeling an onion - each layer you uncover makes you cry a bit more. It will be fair to say that, as much as it is important to understand how to write code in C++, it is also important to understand how not to. However, there are tools and resources available to help you navigate these challenges, and in this book, we try to point you to best practices and potential pitfalls to avoid. Modern development environments also offer a range of features and tools that can help you manage your code, prevent mistakes, and identify problems as they arise. And of course, practice is always the best way to learn and improve your skills. Remember: mistakes are your best tutor - don't be afraid to make mistakes, as they are often the best way for you to learn and grow as a programmer.
1.1.2 Is C++ actually awesome? Some experienced C++ programmers, particularly those who have been working with the language for many years, have expressed their criticism about modern C++, comparing it to the legendary figure of the ‘Golem’ - a creature that rose up against its creator (also known as “The Golem effect”). Some professionals even abandoned C++ and went back to good old C. This criticism has even spawned its own Wikipedia page[2], which outlines the various concerns and objections that these programmers have with the direction that modern C++ has taken. To understand the criticism, let's go back to the early days of C++, as it is a programming language with a long and storied history, having been
developed in the 1970s as an extension of the C programming language. While C++ has undergone many changes and updates over the years, it is still based on many of the same underlying principles and features that were present in its predecessor C. This can be both a strength and a weakness, as the language retains much of its power and flexibility, but it also still includes older features that may be unsafe or outdated in modern programming environments. One way to think about C++ is as an ancient city with old roads and infrastructure that were never designed for modern vehicles and technology. The language was created at a time when developers had to work with 1MB of memory and low computing power, while today computers use no less than 8GB of memory and robust computing power. Initially, C++ was not designed to take advantage of the much larger and more powerful computers that are available today. While C++ has been adapted and updated to meet the needs of modern programming, it is still, to some extent, based on foundations that were laid down decades ago. This can make it more complex and challenging to work with than newer languages that were designed from the ground up with modern hardware and software in mind. If we put aside specific complaints, most of the criticism relates to the complexity and overhead modern C++ may suffer from. While some of these complaints and criticisms might be true, let's remember three key factors: 1. C++ has stood the test of time and is here to stay, despite some criticisms that have been leveled against it. While it is true that C++ can be complex and heavy at times, with a lot of overhead and baggage from its long history, it is also a language that has evolved to meet the needs of a wide range of technologies and applications that were not even imaginable when it was first developed. This adaptability and versatility are something that should be recognized and appreciated, even as we acknowledge the challenges that the language presents. 2. Modern C++ was introduced in 2011, more than 25 years after the original version of the language was first released. While it has been updated and improved to meet the needs of modern programming environments, it is still designed to be compatible with older systems and hardware, as well as less complicated applications. This can
sometimes make it feel cumbersome or awkward to work with and can be perceived as being overly complex or annoying at times. 3. The newest C++20 brought together some brilliant minds to rethink and redesign the language, to provide practical answers and solutions to some fundamental features and issues C++ was carrying since its early days. The result of their efforts was a set of comprehensive changes and modifications that represented the most significant overhaul of the language in its history. These changes are designed to make C++ more practical, efficient, and user-friendly, and they will continue to evolve and expand with the release of future standards such as C++23. The way we see it, C++ is headed in the right direction. To sum up, even if some programmers feel that modern C++ has strayed too far from the roots of the language and has become too complex and unwieldy, it is only natural for any programming language to evolve and change over time. It is also important to note that these criticisms are by no means universal, as millions of C++ programmers continue to use and enjoy modern C++ without any issues.
1.2 Spoken languages Vs programming language C++ is a human-to-machine language, a second language to over 5.4 million people worldwide, with commonalities from the world of computer science. As computers do not understand "humans", we need to use a language which a computer can "understand". Computers "speak" binary, which is basically just an input and output constructed of 0s and 1s. Humans, on the other hand, would carry a heavy burden if they were forced to write complex machine codes using only the 0s and 1s – it would be extremely difficult to write and maintain. To better understand, let's look at Figure 1.1, which shows what the English alphabet looks like in binary. Figure 1.1 The way the English alphabet is represented in binary.
Now, let's look at Figure 1.2 which illustrates machine code written in Assembler (on the right), which is hard to understand and maintain, and the same code written in C++ (on the left). In fact, you don’t need to know C++ to see that the C++ code looks structured more like an understandable set of instructions compared to the machine code. Figure 1.2 A small sample of C++ code and how it looks like had it been written as machine code.
Note
The binary assembly code in Figure 1.2 is specific to the machine architecture and operating system it was compiled for, and might not be directly executed on other systems without modification. good to know
Machine code is typically written in assembly language, which is a low-level programming language that is specific to the architecture of the processor. Assembly language provides a human-readable representation of machine code instructions, using mnemonics to represent the individual instructions and operands. Moving on, and since it would be impractical and inefficient for humans to write complex machine code using binary, we use programming languages such as C++ to write code in a way that is more natural and humanly readable.
Once our code is written, it is passed through a special program called a compiler, which converts the code into a form that can be understood by the computer. This process is necessary because computers are not able to directly execute code written in a human-readable language such as C++. Instead, they require the code to be translated into binary instructions the computer can understand.
1.2.1 Language Evolution: From Grunts to Code Understandably, as computers become more complex, fast, and strong, and as our world becomes increasingly reliant on technology to support this complexity (for better or worst), it’s only natural for a programming language to evolve in parallel with technology itself. However, this might sometime lead to unwanted complexity. In the science of linguistics, language complexity can be characterized as the number and variety of elements and the elaborateness of their interrelation structure[3]. You might be surprised that we mention the science of linguistics in a programming book, but there is, in fact, a strong correlation between linguistics and computer science, which started back in the 1940s and 1950s, when computer science just started to emerge. The rule of thumb is that every language aspires towards simplicity, and so is C++. In human history, the most ancient spoken languages which are still spoken today, evolved into a simplified form, often becoming simpler and more efficient over time. Take ancient Greek for example it evolved into modern Greek, which is simpler and a more streamlined language. Another good example is ancient Hebrew, which is considered to be a very complex language. Ancient (or biblical Hebrew), has evolved into modern Hebrew - a simpler and easier form of the language. Compared to ancient languages like Hebrew or Greek, English is relatively young and less complex. For instance, in English, we only have one pronoun "you" to refer to both singular and plural subjects, while in Hebrew and Arabic, there are four different pronouns for each subject, depending on gender and number.
Essentially, modern languages tend to be simpler and more efficient than older ones. If you need further proof, look around you: people started “speaking” using emojis, and according to linguistics, it is a natural evolution of the way people might be speaking in the future[4]. Programming languages evolve in a remarkably equivalent manner to spoken languages: they aspire towards simplicity and abstraction. In the most basic form, you want to "talk" to a machine and control it, you cannot do it in binary - you need to use "words", expressions, mathematics, and logic. If we look at the changes C++ had throughout the years, we can clearly see that abstraction is the major one. Furthermore, C++20 generated an even greater simplification of the language, turning it into more user (or coder) friendly. In future versions of C++, it will continue this path.
1.3 All the good reasons to learn C++ Mastering C++ is a great root foundation and a valuable investment. The knowledge you will gain from learning C++ can be implemented across many other programming languages. The influence C++, (which was originally written in C), has on other programming languages is huge. How do you think C# was written? C++ of course! Another great benefit is that when you use C++ as a programmer, you have the power to deliver impressive performance and, at the same time, handle complexity with grace. Since C++ can run on all hardware types, it gives you the power to choose your passion and professional path. Do you want to develop games? Networks? Mobile apps? Financial applications? Medical applications? Imaging? Artificial intelligence? Wearable devices? The Mars Rover? The list goes on and on, and C++ is the golden ticket to most of those. There are, of course, other programming languages around which can also open up these worlds for you; but, in many cases, C++ gives you more control and speed over the alternatives. One of the key strengths of C++ is its ability to be used as both an operating system-specific language and a platform-independent language. When used as an operating system-specific language, C++ provides libraries, APIs, and features that allow developers to interact closely with the underlying
operating system, accessing platform-specific functionalities and resources. This level of system-level control is particularly beneficial when building applications that need to directly interface with the operating system, leverage its unique features, or take advantage of hardware-specific optimizations. On the other hand, code written in C++ can be designed to be platform-independent by relying on standard libraries and adhering to crossplatform coding practices. This flexibility makes C++ an excellent choice for developing applications that need to run across different operating systems without significant modifications. It is also important to mention the emerging popularity of C++ and the growing demands for C++ professionals. This is one of the reasons for the growing and growing strong C++ communities, programming forums, and open source (free source code). GitHub, for example, is an open-source hub with a lot of free code samples. Stack Overflow offers articles, free code, Q&A, and much more, and the C++ alliance offers great resources and support for the growing C++ community. As you start your programming career you will most definitely encounter these platforms, and you will always be able to post questions, download code, share, learn, and become an active valuable member.
1.3.1 C++ == Salary++ If we are talking about your career, C++ dominates almost all industries. The list of game-changing applications and technologies which were developed in C++ is long and impressive. Software like Adobe Photoshop and all other Adobe applications, Amazon AWS, PayPal, Oracle, SAP, Google, Firefox, MySQL and so much more were written in C++. And the list goes on and on. Over 1,200 major IT companies are using C++, and this speaks for itself. Mastering C++ is a real career booster as C++ is literally everywhere. Many employers consider C++ a great advantage when candidates master more than one programming language - C++ gives you an edge, as it proves you have a strong set of capabilities that those who do not know C++ might lack. As the common saying goes, "C++ == Salary++” because there is indeed a growing need for C++ programmers, with average salaries ranked among the ten highest in the industry. Start from +$65K for a C++ beginner, going up to
around $118K a year[5]. And no -C++ is not the highest-paying programming language, but it is always ranked somewhere on top. A programming language's ranking usually shifts and fluctuates, but C++ manages to stay stable on the high end of the salary table. Figure 1.3 shows the most indemand programming languages for 2022 according to CodingNomads, which ranked the most popular and rewarding programming languages based on LinkedIn job postings in the US and Europe. The graph awards Python the top spot, followed by Java, JavaScript, C++, C#, C, TypeScript, PHP, Perl, and Ruby, which closes the top 10 list. Figure 1.3 C++ has one of the highest paying salaries when it comes to similar options such as C, Java, and Javascript.
Though there are other programming languages that pay more than C++, bear in mind that languages such as Python, Java, and Java Script are mostly designed for high-level programming, while C++ is used for both high- and low-level programming. It is also important to note that the salaries
demonstrated in Figure 1.3 are average salaries for mid-level programmers, and experienced C++ programmers are known to earn even twice as much. Overall, while salary is certainly an important factor to consider when choosing a programming language to learn, it is only one of many factors, and it is worth considering the long-term value and potential of a language as well.
1.3.2 Sometimes C++ is the less appropriate choice While C++ is a powerful and versatile programming language that is useful in a wide range of contexts, it may not always be the best choice for certain types of projects, such as web programming or the development of lightweight applications. If your primary focus is on web development or front-end development, you might find it more practical to learn a language like JavaScript, PHP, Java, Python, or C#, which are specifically designed for these types of tasks. Some programmers who want to delve even deeper into the world of programming may choose to learn C instead of C++, as it is a lower-level language that provides a greater level of control over the hardware and operating system. However, for the reasons outlined previously, C++ is an excellent choice.
1.4 C++ 20 - in the name of simplification As already mentioned, C++20 (and C++ 23 to come) encapsulates some of the most powerful and key features and modifications are seen so far and is the next generation of modern C+, representing a major step forward in the evolution of the language. C++20 includes some fantastic powerful and innovative features that are designed to simplify and streamline the process of writing code, while also making it more expressive and easier to read. As oldtimer C and C++ users, we were thrilled with some of the new features, which drove us to write beautiful codes in half the effort. If we look at the evolution of modern C++ across all versions (starting from C++11, C++14, and C++17), we can definitely say that C++ 20 encapsulates some of the most profound core changes, not only in the sense of simplification but also in the way it allows you to structure your code, as you will learn in this book. In a way, C++ 20 is considered a game changer.
In this book, we aim to provide a comprehensive introduction to the new features and improvements in C++20. We not only explain what these new features are and how they work, but we also delve into the reasons behind their inclusion in the language and how they can be used to make your code more efficient, expressive, and maintainable. To help you understand the full extent of the changes in C++20, we sometimes provide comparisons with previous versions of C++, so that you can see how the language has evolved over time. While some of the new features in C++20 are quite advanced and require a deep understanding of the language, we provide additional resources and references at the end of the book for those who want to learn more about these more complex features.
1.5 A C++ state of mind Learning the fundamentals of C++ is relatively straightforward, but some advanced features can initially appear intimidating. When embarking on your C++ learning journey, it's essential to grasp the logic behind the syntax, statements, and structure, and how they work together. Hold on to these concepts, especially when dealing with complex code that may seem nonsensical at first. It's no secret that there is a lot of 'brain power' which needs to be invested not only when learning C++, but also when using it in real life. Hair pulling is another common C++ side effect. While other programming languages, such as C#, JavaScript, or Python are easier to learn and practice, C++ does not give you any discounts... In terms of building things, C++ is more like constructing a piece of furniture from scratch, while programming languages like Python or Java are more like purchasing a pre-made piece of furniture from IKEA only in need of assembling. The key difference is that with C++, you have the option to do either one. In other programming languages, there is often a tradeoff between simplicity and control.
If you are into full (or more) control over what is performed at the lowest level, C++ is one of the best choices, and with that control, you can always add layers of functionalities on top of that lower level, giving you simplicity and easiness as well. More simple programming languages might allow you to write code faster, think less, and worry less, but they have specific limits. It is like typing using readymade sentences which were pre-prepared for you, rather than in your own words. Remember
Programming provides you with a set of capabilities and tools to convert tasks and ideas into computer programs. These capabilities and tools are wide and different, allowing you to choose your preferred way of implementing what you want a computer program to do. C++ gives you an even wider range of options. This book exposes you to these capabilities and, with a hands-on approach, teaches you how to become a programmer, how to choose the path you wish to go when you start working on a task or an idea, and assures you that you have what it takes to make the right choice, keeping in mind that the choice is yours.
1.6 Our approach In this book, we take you on a practical and hands-on journey through the world of modern C++20. Our goal is to not only teach you the fundamental concepts and syntax of the language but also to give you a deep understanding of how C++ works and why it is structured the way it is. We use a step-by-step approach that starts with the basics and gradually builds up to more advanced topics so that you can gain a solid foundation in C++ and be able to apply your new skills to real-life projects. Throughout the book, we use a variety of examples and exercises to help you learn by doing, and we also provide explanations and insights into the "why" behind the "how", so that you can gain a deeper understanding of the language and its design principles. Whether you are a beginner programmer or an experienced developer looking to learn C++, this book is an ideal resource for gaining the skills and knowledge you need to succeed.
Developing strong logical thinking skills is crucial for success in programming, particularly when working with a versatile language like C++. The ability to approach problems systematically and find elegant solutions is a key aspect of effective programming. In C++, you'll encounter various approaches to problem-solving, but the most effective ones are often the simplest and easiest to comprehend. Therefore, it's essential to hone your logical thinking abilities and regularly practice applying them to coding challenges. The way we see it, programming is an art form - a creative and expressive way of using technology to solve problems and build new things. Yet, many programmers tend to focus solely on the practical aspects of coding and overlook the artistic and philosophical side of it. In this book, we aim to highlight the beauty and creativity of programming and encourage you to see it as an art form in its own right. In this book, we not only teach you the syntax and concepts of C++, but we also provide exercises and examples that will help you develop your logical thinking skills and apply them to real-world problems. By the end of this book, you will not only have a solid foundation in C++, but you will also have the critical thinking skills that you need to succeed as a programmer, or, even “a code artist”.
1.6.1 Building a solid foundation The truth is that mastering C++ requires time, dedication, and most importantly, a lot of practice. In this book, we hand-craft your skills, as we provide the guidance and resources you need to develop a strong foundation in C++ and grow your skills over time. With our hands-on approach and emphasis on understanding the concepts behind the code, you will be able to craft elegant and effective programs that showcase your capabilities as a programmer. This book will, hopefully, plant the seed from which you will grow your C++ crafting skills. Once you get the hang of it and gain some confidence, you will be amazed at the level of freedom and creativity C++ can offer you as a programmer, so you could literally create, innovate, and build the most amazing programs imaginable.
In this book, we also guide you on how to design, write and develop interesting and practical projects, which will teach you quite a lot and will serve as a great foundation that you can use in your portfolio. So, whether you are just starting on your journey as a C++ programmer or looking to build upon your existing skills, this book is the perfect guide to help you grow and succeed in your craft.
1.6.2 What we expect from you As you embark on your journey to master C++, we encourage you to embrace the challenge and have fun along the way. Learning a new programming language can be a rewarding and fulfilling experience, but it is important to remember that it takes time and practice to develop real expertise. Just as it takes years to become proficient in a spoken language or to master a musical instrument, it will take dedication and perseverance to become a skilled C++ programmer. To ensure that you get the most out of this book and your learning journey, it is important to stay curious and ask questions when something is not clear. Ask "why" a lot - this will lead you to search for the answers which will, eventually, lead you to a better understanding. Don't be afraid to dig deeper and seek out the answers to your questions – this will help you gain a deeper understanding of the concepts and techniques you are learning. And above all, remember to enjoy the process and have fun as you grow and develop your skills in C++.
1.6.3 What you should expect from this book In this chapter, we introduced the basics of C++, a programming language for both low- and high-level programming. We also laid out all the good reasons to learn C++, along with the difference between C++ and other programming languages. Moving forward, rest assured we have used our combined experience to construct a great learning program that will help you understand and practice C++ from the very basics up to solid skills. If you never wrote code before, or have little to no knowledge of computer science, worry not – we will explain every little concept, term, or methodology, and will never take it for granted that you know or understand something unless
we thoroughly explain it. It is enough if you have elementary school math skills to gain all the benefits from this book, and we are sure you will enjoy reading and learning from it.
1.6.4 Making the best out of this book Note that this book is aimed at those with NO previous knowledge or experience with any programming language, or even knowledge of the basics of computer science. This book is also suitable for those who have some experience in other programming languages and are new to C++. All you need to do is to follow this book chapter by chapter and practice a lot. You can also find many great programming skill development sites online, with coding exercises and quizzes, which can help you maintain and grow your knowledge through hands-on experience. Learning C++ using a book is greatly beneficial only if you practice writing real code, and we encourage you to do so. To get the most from this book, focus on the hands-on parts. Spend more time using your selected development environment (IDE), and, during and after each chapter, try to not only write the exercises in the book but also try to invent your own programs based on what you have learned. Try to see the fun in each ability and concept you will be introduced to - it will give you the power to turn your ideas into a working program. The best advice we can give you is to practice, code, and invent. Practice each topic you will be learning. Exercises and code samples are part of each section; code as many variations of what you learn, not only what you are asked to do, but more. The more the better. Then try to invent other ways, other tasks, and other programs using what you have learned. Try to combine different areas and topics from different chapters. When you are working on something you have just learned, try to think: what other things you learned before can be useful now? The best scenario would be using the accumulated knowledge from all previous chapters when working and practicing code based on the current chapter. This book will provide you with all the basic tools and know-how to start your path toward becoming a great C++ programmer regardless of your previous knowledge or experience in C++ and programming, in general.
1.7 Summary C++ is one of the most powerful programming languages out there and can be used for both low-level (closer to the computer's hardware) and high-level programming (the actual visible software, application, or website). C++ is used by almost every IT giant, and mastering it can be a real career booster, including higher salaries. C++ 20 is the most recent evolution of C++, introducing some brilliant and powerful new features which can simplify your code. It is yet another evolution in modern computer programming. There are tremendous advantages to learning and mastering C++, among which is the fact it is a powerful root foundation and a desirable skill for any other programming language out there. There is a tight correlation between spoken languages and computer science, and the resemblance in aspiration towards simplicity and abstraction, which C++ 20 brings us closer to. C++ is not suitable for all programming use cases, and if you are looking into lightweight programming languages, there are better options. Once you master C++, it can become a true form of art, with unimaginable room for creativity. Our journey begins here. Let's pull up our sleeves and start learning the newest and most exciting version of C++! [1]
According to the Developer Economics survey by SlashData. See: https://adtmag.com/articles/2018/09/24/developer-economics-survey.aspx [2]
https://en.wikipedia.org/wiki/Criticism_of_C%2B%2B
[3]
Rescher, Nicholas (1998). Complexity: A Philosophical Overview. New Brunswick: Transaction Publishers. ISBN 978-1560003779. [4]
https://www.bbc.com/future/article/20151012-will-emoji-become-a-newlanguage [5]
According to Indeed.com.
2 Exploring C++ fundamentals This chapter covers Reviewing basic programming concepts Writing your first C++ program Understanding principles of variables and memory allocation Declaring and initializing variables Learning about constant variables and when to use them Understanding the concept of local and global variables In this chapter, you'll learn the fundamental programming concepts, including the role of punctuation, logic, syntax, indentation, and comments in writing functional and aesthetically pleasing code in C++. We'll cover the basics of computer programming and the compiler's function, which transforms your code into machine language, and the IDE (Integrated Development Environment). Additionally, we'll assist you in writing your first C++ program and interpreting every part of your code, allowing you to feel at ease with your first C++ hands-on experience. This chapter will also introduce you to variables and how they aid in overcoming the limitations of human memory and computer storage. You'll learn how to use variables in your code and how to avoid errors by adhering to best practices. We'll also show you how the location of code statements can have a significant impact on your program, whether locally (within the scope of your code block) or globally (outside of the scope of your code block). Finally, we'll teach you how to handle constant variables, which are values that never change. Throughout this chapter, you'll write simple code while gaining confidence in reading and understanding C++ syntax and logic.
2.1 Some basic concepts before we begin Most if not all of the terms explained in this book were created to simplify the computer's work, but we need to help the computer "understand" us.
From the computer's point of view, a program is just a very long list of instructions written by humans, telling them what to do. Such a list can get to millions of lines of code, and the goal of a programming language is to structure and simplify these instructions and mediate us humans with the computer. This is why, on your path to writing and understanding C++ code, it’s important to start with some basic programming and computer science concepts, which are an inseparable part of programming in C++ (as well as other programming languages). So, before we continue our journey, let’s first go through some concepts in computer programming in general, and in C++ in particular. Note
If you are familiar with some or all of these concepts, feel free to move on to the next section.
2.1.1 Your operating system - The wizard behind the curtain The operating system has traditionally been a crucial component in determining the behavior and performance of programs, as programming languages rely on various system resources like system calls, libraries, and more to interact with the operating system. The OS serves as a mediator between software and hardware, offering tailored services to programs for efficient execution. However, with the advancement of technology, the dependency on the OS is gradually diminishing. Online compilers are now available that can compile and execute code without relying on the local OS. Additionally, C++ 20 has made significant strides toward reducing the reliance on OS-specific libraries (APIs) by incorporating more functionalities into the language. For instance, file handling, a crucial aspect of programming, can now be achieved with just a single line of code in C++ 20, making it easier for programmers to work with files without relying on the OS. As time goes on, the OS's role in programming might become less significant, but it still remains a vital component of the computing ecosystem.
2.1.2 Your Console / Terminal – because who needs the mouse? An important term you may find in books, guides, and source code snippets is “Console”, also referred to as “terminal” (In this book, we will only use the term “Console”). In the old days of the DOS operating system, all computers only displayed a black screen with monospaced text, and all interaction with the computer was done via typing a command to that screen and waiting for the result to appear. This is also known as "input" (what you type) and "output" (what the computer types back). Later, when the first versions of Windows and Macintosh appeared, the graphics-oriented interface was born. Today, most users will only use the mouse and keyboard to open windows, drag, select, copy, and paste. Every child is familiar with these actions; however, the old "black window" – a console, or terminal, is still used, especially during the development of a program. Throughout this book, you will be writing code that uses the console as the platform to display and run your programs.
2.1.3 Shhh… libraries In real life, we all know what a library is: a collection of materials, books, or media that are accessible for use and not just for display purposes[1]. Computer programming libraries have a similar definition: they are collections of prewritten code that users can use to optimize tasks. When we program, we often need to perform repetitive or common operations, such as input and output, calculation, reading and writing to a file, searching, etc. C++ comes with a large base of prewritten code, called libraries, which can save you the time and effort of programming these basic operations yourself. Libraries in C++ and other programming languages offer a variety of routines, functionality, and definitions that can greatly benefit your code. Instead of reinventing the wheel, you can use libraries to quickly and easily access prewritten code. For example, a library for creating PDF files can
allow a program to generate and save PDF reports without the need to write the code from scratch. C++ standard library (STD) – the Crème De La Crème of the C++ libraries C++ has many useful libraries that developers can use to build applications for various use cases in the real world, but the Crème De La Crème of C++ libraries must be C++ standard library, also known as std – and you will see and use std a lot throughout this book, including in the C++ code you are about to write shortly. The Standard Library offers a wide set of useful functionalities and methods which can be helpful, using modern, easy-to-use, and efficient algorithms. For example, the iostream library, which is part of the C++ Standard Library, contains all the functionality for input and output streams. If you include the iostream library in your code, you will not need to handle the actual properties or any other code for handling input and output streams. The C++ Standard Library is a huge subject on its own, and in this section, we only introduce you to the tip of the iceberg. Note
Another important and useful library in C++ is the Standard Template Library (STL), which you will learn all about in Chapter 10. Good to know
C++, and many other programming languages, provide the flexibility of not only utilizing their built-in libraries but also allowing you to create and design your own libraries. Developing a library is a skill that requires a good grasp of programming concepts, and this book aims to equip you with the necessary skills to create your own libraries further on in your career.
2.1.4 Header files – no need to reinvent the wheel
Header files contain pre-written code such as functions, declarations, and data structures that are required by your program. These files are pre-processed or pre-compiled, meaning that instead of writing the code from scratch, you can simply include the header file in your program. In fact, libraries in C++ come with several header files. There are frameworkrelated header files, such as , which you just learned about, and which we are about to use. When it comes to libraries, the header file is like a map, that shows us which roads we can take in the library. Each element of the library is declared or defined in the header file (and if you're not sure what "declare" and "define" is – don't worry, we explain these concepts soon enough), and each header file contains specific methods, functions, and helpful capabilities you can use in your code. For example, the header file was added in C++ 20 and is now a part of the C++ Standard Library. offers date and time utilities you can use in your code, such as clock, time points, and duration, and it was an important and useful addition to C++. C++ has many header files, which are part of various libraries, and we teach about a lot of them in this book, but, obviously, cannot cover all of them. To work with header files, we must use the #include preprocessor directive, which tells the compiler to include the contents of a header file in the source code before it is compiled. When you write your first code, you will use the #include directive to include the header file which will allow us to print text to the console (output) and handle input – and we demonstrate and explain it shortly. Good to know
C++ allows you to use its built-in header files, or use your own header files. Designing and writing header files is an important skill we cover later in this book. Note
Header files have some potential pitfalls, such as naming collisions and
dependencies between different modules of a program – and we discuss all that in chapter 15. In Chapter 15 you will also learn about Modules, which were added in C++20, and were designed to replace the way traditional header files are used. However, it's important to note, that Modules are very new and still very new, so they are not well embedded in the C++ language yet, and in any case, understanding how traditional header files work can help in understanding how C++ modules work, as they build upon and improve upon the traditional header system.
2.1.5 Namespace – avoid name conflicts The concept of a namespace is important and will be discussed throughout this book, but in a nutshell, it's a way to better organize code and avoid name conflicts. It's like having two kids named Max in the same class – when you call Max, which Max should answer? but what if we call them Max L, and Max B – the name conflict is resolved. Going back to code, let’s say we have two libraries: One is called lib1, and the other lib2. Both libraries use a function called calculate. If our program needs to use this function – which library should be used? The compiler will simply not know unless we define it explicitly. Namespace solved this problem by attaching each name to a "space" – hence the name "namespace" – it's literally a space for names and we use the library name as a prefix. Think of a namespace as a container that holds variables, functions, and other data types. If we take lib1 and lib2 as examples and use a Prefix, it would be lib1::calculate, or lib2::calculate. In our case, we use the C++ Standard Library, which is named std. This means that to use a function from the standard library, we need to prefix it with std::. For example, to use the cout (“callout”) function for outputting text to the console, we need to write std::cout – and we explain more about that in a second.
2.1.6 keywords In Chapter 1, we mentioned that C++ uses 95 keywords, which are predefined words that have a specific meaning and purpose in the C++
programming language. These words are reserved by the language and cannot be used as identifiers for anything else, but the intended meaning is C++ intended. It's also important to spell the keywords correctly. For example, the keyword int, which represents an integer value, and which you will use in your first code, will not work if it is spelled as Int. There is no need to memorize all 95 keywords, and most programmers don’t know them all.
2.1.7 The important role of your compiler Up to this point, we talked about a programming language, which is in a more "human" form, and machine language, which is what the computer can work with, while humans find it harder and non-friendly. What we didn't really talk about is how programming language converts into machine code. The process of converting human to machine code is actually a complex procedure under the responsibility of the compiler. A compiler is nothing but a program that converts human-readable source code into machine code, which is a binary code that computers can understand and execute. Good to know
The process of converting high-level code into low-level code, or humanreadable code into machine code, involves three main steps: tokenization, parsing, and code generation. In Appendix B we further explain these concepts and terms, and we recommend that you will learn them, as understanding the role of the compiler and how it converts source code into machine code is essential for any programmer.
2.1.8 Your IDE - your power tool Your IDE is your kitchen. It's where you boil, spill, steam, and stew some of your best ideas and brilliant programs. The IDE itself, on the very basic notion, contains an intelligent text editor, or a software environment you use to write, edit, debug, test, and run your code. Some IDEs can interpret what is typed out. Some IDEs display the text in different colors to represent different components, which makes it easier to maintain the code on a visual
level. For example, Visual Studios offers a feature called IntelliSense, which predicts what you are typing and auto-completes it. Some other IDEs offer similar features. Your IDE will also contain your compiler. Once you want to execute your code, the IDE’s compiler interprets it and converts it into machine language, based on the steps you just learned in the previous section. The role of the linker
Another important part of your IDE is the linker. The linker is what produces the final compilation output from what the compiler produced. One of the components the linker links with your program is libraries. As you learned, a library is a set of pre-written commands, functions, and other methods to handle various use cases in your code. Libraries can either be static or dynamic, and it's important to understand the difference between the two. Static libraries are linked at compile-time, resulting in a larger executable file that contains the library's code. On the other hand, dynamic libraries are linked at runtime, allowing the executable to load the library's code only when needed, resulting in smaller executable files. However, in C++, only static libraries can be linked, which applies to all operating systems. The linker ensures that all necessary components, including static libraries, are linked to the right objects, making it possible to generate an executable of our program. If the correct component isn't linked, compilation might be successful, but linking will fail, making it impossible to generate the final output. Which IDE is good for me?
It is important to note that we recommend using Visual Studio (VS), a popular and powerful integrated development environment (IDE) widely used by most developers, and which supports Windows and MacOS (and if you use Linux, VS code is the IDE for you). In our experience, Visual Studio has proven to be very stable and effective with many benefits, such as easy navigation between files, accurate coding with built-in code assistance, rigorous testing capabilities, and customizable options.
Additionally, VS supports almost every major programming language, making it a valuable tool for those interested in learning multiple languages. By learning how to use Visual Studio from the beginning, you will be able to easily transition to other programming languages supported by the IDE, such as C#, Python, JavaScript, Java, and TypeScript. While some programmers also use Visual Studio Code (VS code), which is also a good choice. You are welcome to use either one. Last but not least, using VS can help you develop your skills as a C++ programmer and prepare you for real-world development where many companies and employers use Visual Studio as their primary IDE.
2.2 Ready, set, code: your first C++ program The first step in writing your first code is creating a new project. A project contains all the files you need for your programs (code). We’ll use Microsoft’s Visual Studio to create the project and to write the code, but you can use any other IDE, some of which are free IDEs you can find online (just search for "free C++ IDE"). Another option is to use Visual Studio Code, also known as VS code, which is widely used. You can download a free version of Visual Studio[2]. You can download a free version of Visual Studio Code[3]. As you learn, you will start to get used to your IDE, and you will also learn how to use it to write, edit, view, and run your program. If you need help setting up your IDE, there are plenty of online guides and instructions to help you out. Note
Instructions on how to set up your Visual Studio IDE and open a new console/terminal project can be found in Appendix C.
2.2.1 Start writing your code – write basic and simple code in C++
The program you are about to write will ask the user to rate this book. The user will have to input his/her rating (a number between 1-10), and then the program will display an output of a message together with the user's rating. Before we start to write the actual code, let’s look at the program’s flow first (Figure 2.1): Figure 2.1 The flow of our program is simple: the user is required to input his rating of the book, he types a rating between 1-10 and we then print the rating to the console.
Now, let’s look at the code you are about to write (figure 2.2), exactly as you should type it into your IDE. In the next few sections, we will dissect each and every component and explain how and why you should write your C++ code this way. Figure 2.2 This is what your first C++ code will look like. We numbered each part and we go over
each numbered element in the next few sections.
2.2.2 Step 1: Include the header file To enable input and output functionality in our program, we need to include the header file in C++. This file contains all the necessary code to handle input and output operations. By including this header file, we are utilizing the built-in features and constructs of the C++ language to simplify our programming tasks, saving us the hassle of dealing with input and output streams ourselves. As you may recall, whenever we want to include a header file, we must first type #include, so unless the iostream header file is a default part of your IDE, let's type outside (above) main() : #include
Note
In case your IDE displays a default "hello World" output statement, just remove it from the code. Good to know
there are two ways to include a header file: one is using the angled brackets, for example, #include , and in this case, the compiler searches for the header file in the system directories where the standard C++ libraries are installed and in addition, the directories you specify. The other way to include header files is using double quotes, for example, #include “my_header.h”. In this case, the compiler searches for the header file in the current directory where the source code is located. In other words, the difference between using angle brackets and double quotes "" is the search path used by the compiler to locate the header file.
2.2.3 Step 2 – Know the main() function – your programs’ entry point The main() function is where you place the first instructions you wish to be executed. Since we normally want to use the help of the IDE and the Operating System, the main() function is your entry point, and where we jump in and add our code, but it's not where the program actually starts[4].
What happens behind the scenes stays behind the scenes
It's important to note that when writing a program, certain preparations are made before the main function is executed. These preparations, which are done behind the scenes, involve the initialization of various components that depend on the specific program and IDE being used. Think of it as turning on your computer - there are many preparations that happen behind the scenes before you can start using it: the operating system loads, the drivers for various components (such as the display, keyboard, and mouse) initialize, and various background processes start running. You don't need to worry about these preparations - you just need to wait until everything is ready, and then you can start using your computer.
As a programmer, you don't need to worry about the preparations behind the scenes of your program and can focus on writing the main function and the rest of your code. Once some behind the scene preparations are done, your program calls the main() function, where your portion of your code and logic are placed. Once the main() function ends and the program has finished its course, some additional work is done in the background, which you are blissfully unaware of as well, as it is just cleaning up and shutting down, freeing resources, and marking the program as completed. You can think of it like turning off your computer - the operating system runs some additional tasks in the background, like closing all open programs and files, saving any unsaved data, and shutting down all system services. This entire process is illustrated in Figure 2.3. Figure 2.3 The flow of events when your program runs. Behind the scenes some preparations are made, depending on your program and IDE, then main() is called and your code is executed. Once main() has finished its course, in most cases, some cleanup is done behind the scenes.
Note
Preparations and the way the program work in the background once it finishes its course, depend on the operating system, as well as your IDE, which might have some additional overhead. Step 3 –use a variable as a "storage unit" The next step in writing your first program is to create a storage location to store our input or output values. The values will be stored in the computer's memory, and we use variables to give this memory location a name. Tip
To understand the concept of variables, think of a room with different shelves where you can store different items. Each shelf can be assigned a name, like "books," "clothes," or "electronics." These names serve as identifiers for the shelves, just like variables in programming serve as identifiers for values that can be stored. In our case, the variables will represent the location of the value which the user will input. If the concept of variables is confusing – don't worry, we explain all you need to know about variables later in this chapter. The first variable will be an integer (int) type. Integers (int) handle numerical values, and since we ask the user to input a rate between 1-10 it’s best to use a variable of int type. We also want to give our variable a meaningful name, so let's call it rate. This name makes sense since our variable rate will represent a rating value between 1-10. So let's type inside main() and under the last line (figure 2.4). int rate; Figure 2.4 Start writing your code inside main() and declare your variable 'int'
Note
The part in the code that starts with // and is colored in green is a comment. A comment is not a real part of your code, but rather a reference for your future self and others who might work on the code. We talk a bit more about comments later in this chapter when we go through some of the C++ language building blocks. The next step is to always end a statement with a semicolon ;. The semicolon; is a statement terminator. It marks the end of a statement, indicating that the current statement has ended and that the next statement begins. If you don't declare the end of the statement, your program will not compile. Most IDEs will alert whenever there is a punctuation issue, and your code will not compile. Your code will have a red line indicating a mistake, similar to how Microsoft Word highlights typos in red. Below (figure 2.5) is an example of a highlighted punctuation error in the code we are writing: Figure 2.5 Your IDE will alert in case there is an error of any sort
As you can see in Figure 2.5, the std:: has a red error marker, indicating there's no; in the statement int rate{}. The compiler thinks that the 2 lines are 1, and is therefore compiling your code as if it was all 1 line instead of 2. Think of it as being like a sentence where you forget the full stop. The next sentence will not make sense. Tip
Forgetting to place a semicolon is a 'childhood disease' many beginners to C++ suffer from. Don't worry, soon enough it will become second nature. Steps 4 and 5 – handling the user's input Now we want to print something to the console asking the user to type his book's rating. We already mentioned we are using a pre-built header named , which manages inputs (what the user types in) and outputs (what the program prints out). Now we need to use input and output streams. To use these streams, which are part of the library, we must use two statements: cout and cin. Think of it as a short for "call out" and print something to the console (cout - output), and "call in" asking the user to input something (cin – input). Note
There is a certain way to use std::cin and std::cout statements in our code and we must use the correct punctuation.
Good to know
In C++ cin actually stands for “character input”, while cout stands for “character output”. Using std:: before the cin and cout statements
stands for "standard library" you just learned about. As explained, libraries are a type of program that isn't intended to be used by software users, but instead to be used by other programs. It's like the engine behind your code. As explained, a program can use as many libraries as needed, while each static library is "linked” to the program adding to it the abilities this library provides using the linker. std::
As explained, since we are using C++ Standard Library, std, we must add std:: before the cin and cout statements, as they are part of the std. Don’t worry about the double colon ::, you will learn why it’s there later in this book. When we type std::cout for output and std::cin for input, the compiler will know that the cin and cout we will use are part of the standard library. Using '' (for input)
Many beginners refer to them as "less than – less than" and "more than – more than" signs. The > are in fact operators. You will learn more about operators in the next chapter, but in a nutshell, operators are symbols that tell the program to perform specific operations. In this case, the > operators are part of the cin (the syntax for input) and cout (the syntax for output). Confused? Let’s try and look at these operators from a different, more figurative perspective: think of the > operators as if they were a megaphone. When you cout (call out) the megaphone is positioned outwards, while with cin, it will be positioned inwards (figure 2.6). Figure 2.6 using cin and cout must be accompanied by the > operators. Using the megaphone illustration, you might find it easier to remember which operator represents which stream.
So let's type:
std::cout rate;
As you can see, we also use quotation marks for the output statement. You might have also noticed another part of the syntax: std::endl. endl means end line. Placing std::endl at the end of the statement means the statement will end in this line, and the next statement will appear in a new line. Don't forget to use the semicolon sign; at the end of each statement. We know it all may seem like a lot to learn and remember, and it might even feel confusing, as it might seem like a strange structure and syntax, after all,
this may be your first attempt at a C++ program, but fear not – you will get used to the way C++ code is written and soon it will feel natural to write and read. Note
there is another method to end a line using \n and we will talk more about this method in the next chapter. However, throughout this book, we will use std::endl. Tip
Most IDEs offer hints and code completion to assist the user with recollection and features, such as auto-complete, and many more. This can be extremely valuable for both beginners and novice programmers. You can see that we are using our variable rate for the input of the user. When the code is executed, the user will be prompted to enter a value and that value is assigned to the variable. Why do we need quotation marks when adding textual output?
It's important to remember that any text that we want to display on the console must be inside quotation marks. In our code, we wrote: "How would you rate this book so far? Please rate from 1-10". Why must we use quotation marks? Well, that’s a great question. In our program we use strings. You will learn more about strings in Chapter 5, but, in a nutshell, let's refer to strings as a sequence of letters, or words. Since our code is also written with letters and some words, the compiler needs to tell the difference between the letters we use as part of our code, and which are part of C++ and strings of our own making. Wrapping strings in quotation marks lets the compiler know we are handling strings, rather than a variable or keyword in the code. Remember
quotation marks must always be used when we create a string literal output
statement. Step 6 – let’s print something to the console The next step after we have the user’s input is to display some sort of output. The output can be anything we like, and it can also include the user’s input, as it does in this case: std::cout age; if (age < 18) #A { std::cout B 2. B > A 3. A == B Figure 3.15 illustrates the very basic logic behind the three-way comparison. As you can see, in case AB the function will return a number > 0.
Figure 3.15 Three-way comparison returns 3 possible results, while the old-time comparison would only return 2 possible results out of three.
The immense value of this new operator is the fact that by using it, we consolidate the full set of three conditions into one single sassy query. Good to know
The three-way comparison methodology is also called trichotomy – division
into three categories. We don't always need to use trichotomy in our code, but when we do, the spaceship operator is very handy and can simplify our code a lot. As code is stronger than words, let's look at the two code snippets below, which by now you should be able to read and understand easily. SAMPLE 1: A >' bitwise operator we shift the bits to the right, in this case, 3
places to the right as we use '>>3'
3. Bitwise AND (&) takes two operands. As AND operation is performed on every bit of two numbers. If both the bits are 1, the result of AND operation is 1. If either (or both) of the bits are zero, the result is zero, as the diagram below demonstrates (figure 3.22). Figure 3.22 When we use the '&' bitwise operator if both the bits are 1, the result of AND operation is 1. If both the bits are zero, the result is zero.
4. Bitwise OR (|) takes two operands. As OR operation is performed on every bit of two numbers. If both the bits are 1, the result of OR operation is 1. If both of the bits are zero, the result is zero. If one of the bits is 1, the result is 1 as the diagram below demonstrates (figure 3.23). Figure 3.23 When we use the '|' bitwise operator if either (or both) of the bits are 1, the result of OR operation is 1. Only if both of the bits are zero, the result is zero.
5. Bitwise XOR (^), which stands for exclusive or, takes two operands and requires that both bits are different for the resulting bit to be a 1. As XOR operation is performed on every bit of two numbers. If both the bits are zero, or both bits are 1 (in other words, if both bits are the same), the result of the XOR operation is zero. If anyone of the bits is 1 (in other words: if the 2 bits are different), the result of XOR operation is 1, as demonstrated in the diagram Figure 3.24. Figure 3.24 When we use the '^' if both the bits are zero, the result of the XOR operation is zero. If anyone of the bits is 1, or both bits are one.
6. Bitwise NOT (~) one number is taken as an operand and all the bits of the number are inverted. 1 becomes zero and zero becomes 1, as demonstrated in the diagram Figure 3.25. Figure 3.25 When we use the '~' 1 becomes zero and zero becomes 1.
Going back to our mock interface and checkboxes where we turn the bold, italic, and underline attributes on or off, we can use bitwise operators as the
sample statements below. Note
Below is a small taste of how turning the attributes on and off might look in real code using shifting "formulas"; Even without understanding much, just by looking at the code snippet below, you can get the idea of how bitwise operators shift and the value changes. Personally, though we work with bitwise operators a lot, we don't necessarily remember how to shift them by heart, and we don't expect you to memorize them as well. Thankfully, there are plenty of references online in case you need to get into the bit… If we want to turn on a bit, we can use the statement: Value |= (1U extracts data from the input stream. [1]
https://en.wikipedia.org/wiki/Rashumon
4 Let it flow – Conditions, iteration, and flow control This chapter covers The benefits of a switch-case statement Introduction to loops and iteration Using while, do-while, and for loops The basics of using files in your code C++ offers us various additional methods for controlling the flow of your code based on conditions and outcomes. In this chapter, we uncover more methods. In the previous chapter, you learned about the if-else statement, and how it can control the program’s flow while setting conditions. In this chapter, we explore another way to control the flow of our program using conditions, with the switch-case statements. The switch-case statement offers a more readable way to control the flow of your program through various conditions and potential outcomes, but it also has some pitfalls. Next, we’ll delve into loops or iterations, which allow you to repeat sections of code multiple times. You’ll learn about different types of loops, including while loops that iterate while a certain condition is true, do-while loops that run once and then check the loop’s condition, and for loops that are great for controlling iterations by setting a sentinel or iterating a predefined number of times. We’ll also use for loops to introduce you to the concept of files and work with them in a coding exercise. Finally, you’ll learn about infinite loops, which is a loop state which iterates indefinitely or until someone stops them. By the end of the chapter, you will practice your skills with a code exercise that contains loops, conditions, and logic.
4.1 Switch craft – using switch-case statements
In the previous chapter, you learned about the if-else statements. C++ offers you another way to use conditions in your code – the switch case statement, which can replace the if-else statement. As you learned, in some cases we need to use several, or even multiple nested if statements (if-else within an if-else statement) which might complicate our code. Switch-case is another way to control the flow of your program, replacing if-else in some cases with a simplified code, saving you the need to use nested if statements. is used when you want to check the value of an argument (variable) towards a list of possible values. For example, let's say we have a program that displays the days local street cleaning is provided based on the user's zip code. In this case, we will use a variable that holds the zip code entered by the user and we will need to compare this variable with different outcomes. We can use a classic if-else statement to determine which service will be offered to each zip code. Switch-case
Let’s look at a basic code we can use in this case. Listing 4.1 Code practice – Select service according to your zip code using if-else
#include int main() { int zip{ 10034 }; std::cout zip; if (zip == 10034) { std::cout