C++ Archives | CodeGuru https://www.codeguru.com/cplusplus/ Sun, 18 Sep 2022 16:52:52 +0000 en-US hourly 1 https://wordpress.org/?v=6.3.2 Video Game Careers Overview https://www.codeguru.com/cplusplus/video-game-careers/ Sun, 18 Sep 2022 16:52:52 +0000 https://www.codeguru.com/?p=19434 Has your love of gaming sparked interest in possibly working in the video game industry? If so, here are some of the most popular video game careers you may want to pursue. Careers In The Video Game Industry Searching for jobs in the video game industry can be tough if you have never done it […]

The post Video Game Careers Overview appeared first on CodeGuru.

]]>
Has your love of gaming sparked interest in possibly working in the video game industry? If so, here are some of the most popular video game careers you may want to pursue.

Careers In The Video Game Industry

Searching for jobs in the video game industry can be tough if you have never done it before.
Why? Blame it on selection, as there are so many paths you can take in the industry, making it overwhelming to decide which way you want to go.

To help you get started with your search, we came up with a list of the most common career paths for video game developers people take when looking to break into the video game industry. Find one that you like, and you can begin researching it further to make moves to get closer to your dream.

Before we dive into the various careers the video game industry has to offer, be sure to bookmark our tutorial: How to Become a Video Game Developer to learn more about breaking into the gaming industry.

Video Game Quality Assurance Tester

Contrary to popular belief, a QA tester does not just sit around and play fun and polished video games all day. Instead, they play the latest game builds that are under construction, not close to being finished, missing content, and are usually full of bugs. As they do so, QA testers are supposed to report defects or things that must be fixed to ensure that games are of the highest quality once they get released to the public.

Although game testers are sometimes seen as entry-level positions in the video game world, they play an extremely important role. A QA tester could be seen as a last line of defense before a game is released to the public. If they miss out on bugs or do not do a thorough job, it could lead to hordes of disappointed fans.

If you are unsure how to break into the video game industry, becoming a QA tester may be your best bet. It can help you learn how video games are made and how studios function. From there, you can move on to become a game designer, programmer, producer, or artist.

Some of the tasks you may complete in your typical daily role as a QA tester include:

  • Playing a game build to look for issues and defects.
  • Knowing how to make a defect appear predictably so others can spot and fix it.
  • Typing issue reports into a database or bug tracker and submitting them to the development team.
  • Collaborating with programmers to help fix issues.

Video Game Programmer

When you work as a video game programmer, developer, or engineer, you use programming languages like C++ or Java to tell a computer how to convert content into a playable game.

Out of all the video game industry’s positions, this one is the most technical, so you may want to go to school to get your degree in computer science or something similar before looking for work. If school is not an option, you can teach yourself programming online. You could also get on-the-job experience by applying for an entry-level programming position with a video game company.

Besides technical knowledge, you will need patience and focus to become a video game programmer. With those skills, you could land a high salary, as programmers are usually the highest-paid positions in the industry.

Here are some daily video game programmer tasks you could experience:

  • Researching, drawing diagrams, and collaborating with programmers before coding a game.
  • Collaborating with team members to discuss how game features should function.
  • Typing instructions as source code via an IDE (integrated development environment).
  • Making sure games work as intended and tweaking source code when needed.
  • Optimizing game performance.
  • Implementing game features.
  • Fixing issues from bug reports received from QA testers.

We have a list of the Best Online Courses to Learn Game Development that can help you get started as a video game programmer.

Video Game Designer

If you have plenty of experience playing video games and love to analyze and discuss them with others, a career as a game designer might be right up your alley.

Do most people start as video game designers? No, as it can be tough to break into such a desired spot without any industry experience. Instead, game designers typically start as production assistants or quality assurance testers. Once they make connections and show they have the potential talent to design games, they can then move into that coveted role.

However, if you are dead set on becoming a pro game designer right out of the gate, you could take the plunge to create games on your own or enroll in a video game design school to get a certificate or degree.

Most video game designer jobs tend to break down into the following categories:

  • Overall game design
  • Mission design
  • Level design

Unity Game Development software
Example of Unity Game Development Tool

If you work on a massive game, your role may be even more specified, and you may find yourself in a position working on pacing, tuning, or combat design.

Here are some tasks you may tackle on a typical day as a game designer:

  • Play a game’s current version to see how it could be improved and ensure it is enjoyable.
  • Test competitors’ games to see their strengths and weaknesses.
  • Design gameplay mechanics and game levels.
  • Create or tweak a game’s numeric data using tools like Microsoft Excel.
  • Balance and tune gameplay.
  • Draft game design documents that help your team understand what you have created.
  • Collaborate with producers, artists, and programmers regarding your current game designs or future projects.

Video Game Producer

A video game producer plays many roles and requires excellent communication and planning skills. Being good with numbers can help, too, as you may be in charge of managing a game’s budget.

You can work your way up to a producer job by starting as a game tester or production assistant. From there, you could get promoted to associate producer, where you focus on scheduling and other daily tasks versus having a say in a project’s overall bigger picture. Move up to a senior producer position, and you can become a product owner responsible for a game’s finances, long-term planning, etc.

Here are some everyday tasks you may have to tackle if you become a video game producer:

  • Ensuring your team has everything they need to be focused and productive.
  • Collaborating with your team to plan the next few weeks of work.
  • Negotiating contracts.
  • Maintaining budgets.
  • Meeting with non-team members like publishers and studio directors.

You may also consider project management tools if you pursue this video game job. Our article Best Project Management Software for Game Developers can help you choose the right one.

Video Game Artist

An artist/animator is one video game industry position that can be tough to crack since it takes a ton of unique artistic talent. But beyond that talent, you must also have skills working with art tools like Adobe Photoshop and Autodesk Maya. Combine all of the above with a strong portfolio, and you may find yourself living the dream as a video game artist doing filling one of the following specializations:

  • UI artist – Plays a crucial role in designing a game’s navigational components, such as the menus.
  • Concept artist – In charge of imagining and planning how a game’s world and characters will look and feel.
  • Character modeler – Creates 3D models of a game’s characters.
  • Character animator – Brings those 3D character models to life.

Other specializations you could work in as a video game artist include visual effects, environments, character rigging, etc. If this sounds like an exciting career path, start looking into art school, as a degree from there could help you get in the door.

Read: Top Tools for Video Game Developers

The post Video Game Careers Overview appeared first on CodeGuru.

]]>
Dealing with non-CLS Exceptions in .NET https://www.codeguru.com/dotnet/non-cls-exceptions-dot-net/ Fri, 05 Aug 2022 20:34:06 +0000 https://www.codeguru.com/?p=19370 In this .NET programming tutorial, developers will learn how to deal with non-CLS exceptions in .NET. First, for the uninformed, an exception is an error that occurs during application execution. Typically, exceptions are caught using a Try-Catch block, as demonstrated in the following code example: using System; class OJExceptionTest { public static void Main() { […]

The post Dealing with non-CLS Exceptions in .NET appeared first on CodeGuru.

]]>
.Net Tutorials

In this .NET programming tutorial, developers will learn how to deal with non-CLS exceptions in .NET. First, for the uninformed, an exception is an error that occurs during application execution. Typically, exceptions are caught using a Try-Catch block, as demonstrated in the following code example:

using System;

class OJExceptionTest
{
   public static void Main()
   {
      int numberOne = 0;
      try
      {
         int numberTwo = 100 / numberOne;
      }
      catch (ArithmeticException ex1)
      {
         Console.WriteLine($"ArithmeticException Output: {ex1}");
      }
      catch (Exception ex2)
      {
         Console.WriteLine($"Generic Exception Output: {ex2}");
      }
   }	
}

In the above example, an integer variable named numberOne was created and initialised to 0. Inside the Try block, a new variable named numberTwo tried to divide 100 by 0. Because it is impossible to divide any number by 0, an ArithmeticException Catch catches this exception, specifically. Below the ArithmeticException Catch block, a general Exception Catch block will be called when any other error occurs.

It is considered good practice to catch specific exceptions, instead of only using a generic exception handler. The output of the above code would like the following:

ArithmeticException Output: System.DivideByZeroException: Attempted to divide by zero.
   at OJExceptionTest.Main()

Read: C# Tools for Code Quality

How to Deal with non-CLS Exceptions in .NET

Non-CLS exceptions, or non-exceptions, are exceptions that do not derive from Exception. .NET does not allow developers to throw non-exceptions; however, .NET does allow programmers to catch them.

These types of exceptions can be caught (and handled) in two ways. First, by using the RuntimeWrappedException within a catch block. RuntimeWrappedException wraps an exception that does not derive from the Exception class.

An example follows. This code example uses C# and calls the C++/CLI library:

var exampleClass = new CLibraryClass.ClassName();

try
{
    exampleClass.ThrowNonException();
}
catch (RuntimeWrappedException e)
{
    String s = e.WrappedException as String;
    if (s != null)
    {
        Console.WriteLine(s);
    }
}

In the above code, we reference a class from a C++/CLI library, then throw an exception from that class in order to make use of RuntimeWrappedException to catch the exception inside the C++/CLI class.

Another example follows, this time using a bit of C++ code to handle the exception:

using namespace System;
using namespace System::Runtime::CompilerServices;

[assembly:RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)]; 

void TryToCatchException()
{
    try
    {
        throw gcnew String("Test string");

    }
    catch(RuntimeWrappedException^ e)
    {
        Console::WriteLine("RuntimeWrappedException!");
    }
}

int main()
{
    TryToCatchException();

    return 0;
}

General Catch Blocks in .NET and C#

The second way to deal with these types of errors is to make use of a general catch block without an exception type specified, which is placed after all other catch blocks. This is demonstrated in the following C# code example:

var exampleClass = new CLibraryClass.ClassName();

try
{
    exampleClass.ThrowNonException();
}
catch ()
{
//The non-Exception will be caught here
}

Read more .NET programming tutorials and software development guides.

The post Dealing with non-CLS Exceptions in .NET appeared first on CodeGuru.

]]>
Online Courses to Learn Video Game Development https://www.codeguru.com/cplusplus/video-game-development-courses/ Fri, 08 Jul 2022 16:30:10 +0000 https://www.codeguru.com/?p=19337 The video game development market is showing no signs of slowing down, helped in part due to the pandemic, as people sought alternate ways to keep themselves occupied with limited access to pre-pandemic entertainment (movie theaters, concerts, packed arenas breathlessly watching mimes). In addition, gaming has been embraced by the world and no longer just […]

The post Online Courses to Learn Video Game Development appeared first on CodeGuru.

]]>
Game Development Courses

The video game development market is showing no signs of slowing down, helped in part due to the pandemic, as people sought alternate ways to keep themselves occupied with limited access to pre-pandemic entertainment (movie theaters, concerts, packed arenas breathlessly watching mimes). In addition, gaming has been embraced by the world and no longer just a hobby for the “uncool” kids.

With the continued rise in interest for video games, it follows suit that the need for people to create those games is on the rise as well. Video game developers are the backbone of game development, and work alongside storytellers, level designers, artists, voice over talent, and game testers to make the world of their games come to life. To do that, however, a developer needs a specific skill set, beyond the normal software development fundamentals.

Seeking a career in game development will require programmers to make a few decisions early on that could shape their career path. For example, video games can be programmed using a number of programming languages, with the most common being C++, HTML5, C#, Java, and Python. Figuring out the platform you want to code games on matters too. If you want to make games for consoles like the PlayStation or Xbox, then C++ is a must. Online game devs will fair well with HTML5; the same could be said for VR (Virtual Reality) and AR (Augmented Reality) game creators.

Top Online Courses to Learn Game Development

Normally in articles that highlight courses to learn a programming language, we break the listings down into categories for beginner, intermediate, and advanced developers. This time we are taking a different approach and giving coders game development courses covering different languages, game engines, and career paths. At the end of the day, you might want to consider taking several of these courses, as the more experience, game development environments, and languages you have under your belt, the better.

Game Writing: Storytelling through Video Game Design from Udemy

Just as with regular programming, knowing syntax, keywords, methods, and functions are great, but they are not all a developer will need to know to become a great software engineer. Program design and an understanding of software architecture are essential concepts for a programmer to know. For that reason, we start off our listing of video game development courses with a surprising entry: Game Writing: Storytelling through Video Game Design.

This game developer course involves zero coding or programming languages. Instead, it sets its eyes on one of the most vital parts of a video game: storytelling and game design. If you have ever played retro video games, you will know that only a few of the thousands that were created ever stood the test of time, regardless of poor graphics and limited memory/processor resources. Super Mario Brothers, Zelda, and Duck Tales were all stand outs not because of superior graphics, but because of solid game design. Symphony of the Night is a revered cult classic from the Castlevania series largely due to its immersive story and replayability.

This programming course teaches students how to write video games and design them. You will study how story is conveyed through gameplay and examples of memorable narrative elements. By the end of the class, students will be able to develop a video game idea from conception through to the story phase. The course is two hours total, with bonus material promised at later dates.

You can sign up for this quick game development course by visiting its page on Udemy: Game Writing: Storytelling through Video Game Design.

Unreal Engine 5 C++ Developer: Learn C++ & Make Video Games from Udemy

The Unreal Engine 5 C++ Developer: Learn C++ & Make Video Games course is great for new developers that want to not only learn video game development, but also the basics of C++ and the ever-popular Unreal Engine.

One of the best things about this particular course is that, by the end, you will have made 5 basic video games. This means that you won’t just be learning code and code principles; you will be actually putting your knowledge to work, helping ensure that what you learn sticks and makes sense in the real world of coding.

The course is pretty long, weighing in at nearly 30 hours. It comes with a “Certificate of Completion” once your finish the class. Video game development topics covered include:

  • How to use (and make games in) Unreal Engine
  • Object-oriented Programming (OOP) principles and concepts
  • C++ fundamentals and best practices
  • Writing clean code and documentation
  • How to use artificial intelligence (AI) for behavioral programming of NPC and enemy characters
  • How to use Blueprint
  • Game development technologies and techniques

You can sign-up for this course and begin creating your first five video games by visiting its Udemy listing: Unreal Engine 5 C++ Developer: Learn C++ & Make Video Games.

Introduction to C++ Programming and Unreal from Coursera

If you are looking for a shorter course to learn both C++ and the Unreal Game Engine, Coursera has a course titled Introduction to C++ Programming and Unreal that may be a better fit before you tackle something larger.

The course does suggest you have knowledge of programming in some language, as C++ (even at the beginner level) can be a little challenging. The course is 20 hours long and is the first part of a larger series called the C++ Programming for Unreal Game Development Specialization. It is made up of four modules, detailed below:

  • Module 1: Create a C++ console app and Unreal Script
  • Module 2: Store and use data in your programs
  • Module 3: Uses classes and objects to create object-oriented code
  • Module 4: Learn how to use the Unreal Engine

You can sign-up for this course by visiting its page on Coursera: Introduction to C++ Programming and Unreal.

Introduction to C# Programming and Unity from Coursera

The Introduction to C# Programming and Unity from Coursera shifts focus from C++ and Unreal and, instead, cover C# and the Unity Game Engine, which is another popular game development tool. One of the great benefits to this course is that it teaches students how to code in C#, which is one of the world’s top 5 programming languages. C# is also highly flexible and powerful, so if you cannot find a job developing games, you will have plenty of other options.

The course is 19 hours long and does not require you to know any programming or software development at all. The course contains four modules with specific goals for each module:

  • Module 1: Write a C# console application and some Unity scripts
  • Module 2: Learn how to store data
  • Module 3: Use classes and objects in C#
  • Module 4: Learn how to create basic 2D games using the Unity engine

You can sign up for this C# game development course by visiting its Coursera listing: Introduction to C# Programming and Unity from Coursera.

The Hands-On Game Development Bundle: Make Your Own Games! From TechRepublic Academy

The The Hands-On Game Development Bundle: Make Your Own Games! bundle is made up of 10 courses, each of which cover an important aspect of game design and development. This is a particularly interesting bundle, because students will get to make several types of games on different gaming platforms and even use a few different game development tools.

In the first course, the focus will be on how to program a micro-strategy game. The second course covers C++ programming for beginners. With a little C++ syntax under your belt, it is time to look at another set of tools for game creation: Node.js and Express. From there, Godot game development is taught, followed by an overview of humanoid animation tools, which are used to animate characters in your games.

With these skills learned, you will next create an actual augmented reality (AR) game called Space Shooter. Unit movement is then covered, after which you get the opportunity to create your first 3D game using Unity. The final two courses in the bundle tackle two more game types: mobile game development and how to use C++ to make a text-based role-playing game (RPG).

To signup, visit the game development course’s page at TechRepublic Academy: The Hands-On Game Development Bundle: Make Your Own Games!

The 2022 Premium Learn Game Development Bundle from TechRepublic Academy

The The 2022 Premium Learn Game Development Bundle is another huge bundle. While it contains fewer courses than our previous listing, it contains an astonishing 130 hours worth of material. A great part of this bundle is that it focuses on other elements of game development and design that other courses tend to skim over. For example, one of the courses covers 2D game creation in Unity, while another teaches 3D modeling with Blender.

Design patterns are gone over in great detail and there is plenty of C++ coding as well. Finally, an “RPG Core Combat Creator” section teaches C# and intermediate level Unity.

To learn more and begin taking this game creation course, visit its TechRepublic Academy page: The 2022 Premium Learn Game Development Bundle.

How To Get A Job In The Video Game Industry from TechRepublic Academy

Learning game development principles, programming languages, and how to work with game development tools like Blender, Unity, and Unreal Engine are all integral parts of becoming a game developer. However, if you do not know how to showcase those skills, network, and create an eye-catching portfolio, none of it will matter. Because of that, we decided to close out this article with the How To Get A Job In The Video Game Industry course from Udemy.

As the name implies, this course will teach you the following career development techniques and tactics:

  • How to stand out from other candidates to ensure your get an interview
  • Interview techniques and answers to common game developer interview questions
  • How to create a brand for self-promotion
  • LinkedIn networking strategies and how to catch the eyes of decision makers
  • How to create resumes, cover letters, LinkedIn profiles, and portfolio that are tailored to the gaming industry
  • Learn how to find jobs and create opportunities when they do not exist

You can sign up for this course to get your career as a game developer started by visiting: How to Get a Job in the Video Game Industry.

The post Online Courses to Learn Video Game Development appeared first on CodeGuru.

]]>
Best Online Courses to Learn C++ https://www.codeguru.com/cplusplus/c-plus-plus-online-courses/ Sat, 25 Jun 2022 21:20:20 +0000 https://www.codeguru.com/?p=19319 In our last go-round, we listed some of the best online courses for C# programmers to hone their craft and get better at developing applications in .NET. This time around, we are going to review some of the top classes to learn C++. We will look at classes in two main categories: those for beginners […]

The post Best Online Courses to Learn C++ appeared first on CodeGuru.

]]>
C++ Variables and Data Types

In our last go-round, we listed some of the best online courses for C# programmers to hone their craft and get better at developing applications in .NET. This time around, we are going to review some of the top classes to learn C++. We will look at classes in two main categories: those for beginners to C++ and programming in general and courses for intermediate to advanced level C++ programmers who want to take a deeper dive into the language and its abilities.

If you are interested in learning C#, be sure to check out our tutorial: Best Online Courses to Learn C#.

Top Online Beginner Courses to Learn C++

The C++ courses in this section are tailored to those that are either brand new to developing software in general or those that know another programming language and want to add C++ as another tool to create apps in.

Beginning C++ Programming – From Beginner to Beyond from Udemy

The Beginning C++ Programming – From Beginner to Beyond developer course from Udemy is a bit beyond your average beginner course (as the title suggests), but it does not cover material so far outside of the realm of the beginner that we thought it would not fit into this category. It focuses on modern C++, and, specifically, C++14, C++17, and bits and pieces of C++20.

Within the 46 hours of on-demand instructional video, programmers will have access to 53 downloadable resources, 2 articles on C++ basics, and 37 coding exercises, complete with coding challenges and assignments to test your knowledge and make sure you are retaining what you learn.

Course takers will learn how to install C++, how C++ programs are structured, what variables, constants, and data types are, how to work with strings, control structures, and many other basic C++ coding principles. More intermediate topics, such as object-oriented programming – or OOP – and how to use Lambda Expressions are also part of the curriculum.

You can learn more about this online course for beginners by visiting: Beginning C++ Programming – From Beginner to Beyond.

C++ Fundamentals: Game Programming For Beginners from Udemy

While most online programming courses teach the same basic foundational concepts, some of the more useful C++ classes take an approach that teaches you a specific career path, which is much more useful in a real-world scenario. The C++ Fundamentals: Game Programming For Beginners from Udemy course takes this direction, as it teaches newer coders how to create video games – which makes sense, because C++ is probably the best option for video game development.

This course is a little shorter than some others, partially due to the fact that it is focused on a specific developer career path. It consists of 11 hours of video, 3 articles, and two downloadable resources. In specific, video game developers will learn how to perform the following tasks in C++:

  • C++ programming fundamentals such as variables, loops, control statements, and more
  • Basic object-oriented programming concepts
  • How to work clean code and use best coding practices
  • C++ debugging and error handling
  • 2D animation
  • C++ game libraries
  • How to compile and run C++ apps

To learn more, visit the Udemy page for C++ Fundamentals: Game Programming For Beginners.

Complete C Family Programming Bundle from TechRepublic Academy

The more programming languages that a software developer or software engineer has knowledge of, the better their career options will be and, potentially, the more money they can make. C++ is a part of the C-family of programming languages, which is made up of C, C#, and C++. These languages all have similar features and work well in conjunction with one another. Also, they are a great lead-in to learning Java, which is one of the world’s most popular and widely-used programming languages.

The Complete C Family Programming Bundle takes the approach of teaching not just the basic of C++, but the basics of C and C# as well. Further, the bundle teaches Intermediate and Advanced C#, and a fully comprehensive C++ foundation.

By the end of this 6-course programming bundle, developers will have the knowledge to get a job as a C# or C++ developer and be able to develop their own full-fledged applications to build a portfolio to show potential employers.

Learn more about TechRepublic Academy’s Complete C Family Programming Bundle.

Top Intermediate to Advanced C++ Courses

The courses below are all designed to teach would-be C++ programmers how to code intermediate and advanced C++ applications. While some offer introductory sections, students can feel free to skip those sections and dive right into the more complex material. Or, if they prefer, they can refresh their memory on the fundamentals of C++, as the courses are designed in a modular fashion.

Learn C++ Programming – Beginner to Advance – Deep Dive in C++ from Udemy

The Learn C++ Programming – Beginner to Advance – Deep Dive in C++ course comes to us from Udemy, like several other programming courses in our list. The course is a little more than 30 hours long and comes with a whopping 289 downloadable resources, 30+ hours of video, and 48 coding exercises to ensure students are retaining the information they are learning. Upon complete, course-takers do receive a Certificate of Completion, which is a nice addition.

You can expect to learn everything from beginning C++ programming concepts like variables, strings, math operators, and commenting to more difficult software development subjects like exception handling, working with objects and classes, and STL. The version of C++ in this course is C++11.

Want to learn more or sign-up for the course? Visit the Udemy page for Learn C++ Programming – Beginner to Advance – Deep Dive in C++.

The C++ Programming Bundle: Beginner to Expert from TechRepublic Academy

TechRepublic Academy’s The C++ Programming Bundle: Beginner to Expert course is actually three courses in one, driving students from beginning through intermediate and on to advanced C++ software development topics.

The first portion of the series walks developers through the basics of developing an application in C++ – from simple concepts like data types through object orientation. At the end, students will learn how to make a particle firing program, ensuring they have a solid foundation of video game development techniques.

The second part of the tutorial series covers the Standard Template Library (STL), memory management, and how to work with structures like lambda expressions, binary file handling, smart pointers, and fractal imagery.

Finally, the advanced portion covers the same topics as the intermediate section, only in much more detail.

To learn more about the popular online C++ course, visit its page at TechRepublic Academy: The C++ Programming Bundle: Beginner to Expert.

The post Best Online Courses to Learn C++ appeared first on CodeGuru.

]]>
Benefits of Programming in C++ https://www.codeguru.com/cplusplus/benefits-c-plus-plus/ Fri, 04 Mar 2022 05:39:09 +0000 https://www.codeguru.com/?p=19021   C++ is one of the oldest and most widely used programming languages in the world. Part of the C-family of programming languages, it regularly places in the top five of the famed Tiobe Index, which ranks programming languages based on developer preference and usage. It is used in a wide breadth of software applications, […]

The post Benefits of Programming in C++ appeared first on CodeGuru.

]]>
 

C++ programming tutorials

C++ is one of the oldest and most widely used programming languages in the world. Part of the C-family of programming languages, it regularly places in the top five of the famed Tiobe Index, which ranks programming languages based on developer preference and usage. It is used in a wide breadth of software applications, including desktop software, graphical user interface (GUI) apps, Operating Systems, embedded systems, and video game software. In today’s programming tutorial, we will look at the advantages and benefits of developing software in C++.

What is the C++ Programming Language?

C++ is a general-purpose, statically-typed programming language with elements of object-oriented programming (OOP) and functional development. It is part of the C-family of languages, and, in fact, is an extension of C originally conceived of as C with Classes – a nod to the fact that it allows developers to use classes and objects in their code. The actual ++ portion of the name comes from C’s ++ or incremental operator, a sort of programmer joke about C++ being an incremental step-up from C. The language was created by Bjarne Stroustrup and developed by the ISO/IEC Joint Technical Committee back in 1985.

The current stable release is version C++20, which came out in December of 2020. The Preview Release – C++23 – was released in October of 2021.

In addition to objects and classes, C++ also incorporates other OOP elements, including inheritance, encapsulation, abstraction, and polymorphism. Despite this, C++ is not always considered an OOP language. It is argued that, while you can use the object-oriented aspects of C++, you do not have to. Instead, developers can take a procedural or functional programming approach to C++ software development.

Read: How to Operate on Strings in C++

What Kind of Software Can You Develop in C++?

C++ can be used to develop a wide array of software, including applications such as:

  • Video Games for consoles like PlayStation and Xbox, as well as games for PC
  • Database software
  • Operating Systems
  • Embedded systems and the Internet of Things (IoT) apps
  • Internet Browsers
  • Graphical User Interfaces and GUI-based software
  • Cloud-based software
  • Enterprise apps

Examples of software created primarily using C++ include Adobe Photoshop, MySQL database, the Mozilla Firefox Internet browser, and, perhaps not surprising, the Windows operating system.

What are the Benefits of C++

There are many reasons to use the C++ programming language to develop software and applications. Outside of its popularity and wide range of use cases. We highlight just a few of the many advantages and benefits of using C++ below.

Compatibility with the C Programming Language

Given that C++ is a derivative or extension of C and, in fact, uses practically all of the C syntax, it is no surprise that C++ is highly compatible with C. If there is a valid C application, it is compatible with C++ by its very nature.

Read: C# for Beginning Programmers

Community and Resources

As one of the oldest, most popular programming languages, C++ enjoys a vast community of developers. A large portion of that community helps add to the continued functionality of C++ by creating libraries that extend the language’s natural abilities. That same community also frequently engages in social media channels, forums, and other online (and offline) communities, helping to troubleshoot issues, provide tutorials, and document the ins and outs of the language. Because of this, it is pretty simple to find answers or solutions to problems in your code or to troubleshoot and debug your C++ applications.

Additionally, since the language is so widely used, it provides a level of job and career security, as the language will not fall off the face of the Earth in the foreseeable future, and, indeed, will continue to be supported and updated.

Platform Independent and Portability

C++ is platform-independent and portable, meaning it can run on any operating system or machine. Because of this, programs developers create in C++ will not be limited to a single OS environment or require any further coding to work on other operating systems. This increases the programmer’s audience reach and limits the amount of iterations of an application a coder will have to make.

Memory Management

With C++, developers have complete control over memory management, which, technically counts as both an advantage and a disadvantage of programming in C++. It is a bonus to developers because they have more control over memory allocation. It is a negative in that the coder must be responsible for the management of memory, instead of giving that task to a garbage collector, as other programming languages do.

Embedded Systems

As noted, C++ is a derivative of C. C, in turn, is a procedural language capable of low-level manipulation. It is similar to machine language, and because of that, C is a great option for working with embedded software and the coding of smart devices, firmware, and even compilers.

Scalability

Scalability – the ability to scale an application to serve varying degrees of users or purposes – is an important element to any modern piece of software. C++ programs are highly scalable and capable of serving small amounts of data or large amounts of information.

Read: Top IDEs and Code Editors for .NET Developers

C++ Standard Template Library (STL)

C++ has the Standard Temple Library (STL) that provides libraries – or functions – of pre-written code that developers can use to save time instead of writing common functionality in their software. These libraries make coders more efficient, type fewer lines of code, write quicker programs, and avoid errors.

Execution and Compilation Speed

C++ is a fast programming language in terms of both execution and compilation. The speed for both is much quicker than with other general-purpose development languages. Further, C++ excels at concurrency, which is important for critical mass servers, web servers, databases, and other types of servers.

C++ Hello World Example

In traditional programming tutorials, the first program a developer will learn to write in a given language is known as the “Hello, World!” application. It is a simple snippet of code that serves as a way for a coder to introduce themselves to the “world”. Think of it in the same way that most guitarists are taught to play “Smoke on the Water” by Deep Purple – it is a right of passage for programmers.

The “Hello, World!” app does not do anything spectacular – it simply prints the words “Hello, World!” to a user’s screen. Here is an example of how to write the infamous “Hello, World!” application in C++:

// C++ program that will “write “ "Hello, World!" to the user’s screen
 
// Header file for I/O functions
#include 
// The Main() function is where execution of an application starts
int main() {
    // prints Hello, World! To the user’s screen
    std::cout << "Hello, World!";
     return 0;
}

Note that the double forward slashes // are used to write comments in your code in C++. These comments are not read by the program and ignored, being only visible to developers. Comments are used to leave notes to yourself or other programmers that may be viewing your code and trying to figure out its intended use at a later date.

Read more C++ programming tutorials.

The post Benefits of Programming in C++ appeared first on CodeGuru.

]]>
An Introduction to Sequence Containers in C++ https://www.codeguru.com/cplusplus/an-introduction-to-sequence-containers-in-c/ Fri, 31 Dec 2021 08:15:00 +0000 https://www.codeguru.com/uncategorized/an-introduction-to-sequence-containers-in-c/ In C++, sequence containers are a group of template classes used to store data elements. Because they are template classes, they can be used to store any data elements, including custom classes. The data structure they implement enables sequential access. There are five sequence containers offered by the C++ Standard Template Library. They are: array, […]

The post An Introduction to Sequence Containers in C++ appeared first on CodeGuru.

]]>
C++ Tutorials

In C++, sequence containers are a group of template classes used to store data elements. Because they are template classes, they can be used to store any data elements, including custom classes. The data structure they implement enables sequential access.

There are five sequence containers offered by the C++ Standard Template Library. They are: array, vector, deque, forward_list, and list. The container classes array, vector, and deque are implemented by using an array data structure. And the container classes, list and forward_list, are implemented using a linked list data structure. The basic difference between these two types of data structures is that arrays are static in nature. This means the size of the container is fixed and set during compilation, although there is a provision to increase the size of the requirement. The linked-list implementation is purely dynamic in nature. The container increases its size with each new element stored in it.

Read: Understanding Containers in the C++ Standard Template Library

Design of the Sequence Container in C++

Each container has a certain unique capability and adds value when culled appropriately to the requirement.

According to Bjarne Stroustrup: “The C++ standard library containers were designed to meet two criteria: to provide the maximum freedom in the design of an individual container, while at the same time allowing containers to present a common interface to users. This allows optimal efficiency in the implementation of containers and enables users to write code that is independent of the particular container used.”

The array containers are an indexed-based structure. The size of the structure is clearly mentioned and set during compilation time. This means it is static in nature. It is quick to create but may waste a lot of space if a chunk of space remains unused. They typically are sequential memory locations under a common name. Although the size is fixed initially, the containers modeled with an array are sometimes resized to accommodate the insertion of elements if the array exceeds its initial size. Because array sizes are set during compilation, a dynamic extension of it is a performance tradeoff. Retrieving elements is easy; we can quickly refer to any elements by the index number. Therefore, fetching the last element does not require traversing of all the intermediate elements.

The linked-list is a reference implementation where a node contains the data element and reference context to point to the next element is implemented as a singly linked-list and both the previous and next elements are implemented as a doubly linked-list. The nodes are dynamically created only when needed. As a result, there is no redundant space to waste. Each node created is linked to the chain or list of nodes. This clearly is an efficient management of space, but note that storing every new element has to create a new node prior to that. This consumes extra time. The retrieval process is also comparatively slow, because, unlike an indexed structure-like array, there is no way to jump between elements. The nodes are dynamically created and allocate non-sequential memory locations only linked by the reference element of the node. Therefore, to pick an element, we must traverse through all the nodes prior to it. In the worst case, we may have to traverse through all except the node we want to get the element. Insertion and deletion also have a time tradeoff.

Now, let us take one container at a time and explicate the idea in a bit more detail.

Read: Understanding the Utility Components of the C++ Standard Template Library

The array Sequence Container in C++

In essence, the array sequence container is nothing but a class representation of a C-style array data structure. But, there are some improvements made by C++. Because it is a template class representation, it keeps information about its size. This serves two purposes: one, we may not provide a size when creating it because the constructor is always able to create one with the default size provided in the class property or we can provide one explicitly. Secondly, we can always refer to its size property to know the exact size of the array. Another important distinction is that the C-style arrays can be easily be treated as a pointer. This can be confusing at times. But, with the class representation of an array in C++, there is no such confusion. Above all, the array sequence container class leverages reliability and efficiency. Otherwise, it can be treated as a simple and static implementation of C-style contiguous memory location only in a more reliable way.

A Quick Example of an Array Sequence in C++

#include <iostream>
#include <iomanip>
#include <array>
#include <iterator>

using namespace std;

int main()
{
   array<int, 7> arr = { 0, 1, 1, 2, 3, 5, 8 };
   array<int, 7>::iterator iter;

   for(iter = arr.begin(); iter < arr.end(); iter++)
      cout<<*iter<<" ";

   cout<<endl;

   iter = arr.begin();
   advance(iter,4);
   cout<<*iter<<endl;
   auto pa = prev(iter,2);
   cout<<*pa<<endl;
   auto pb = next(iter,1);
   cout<<*pb<<endl;
   cout<<"Size : "<<arr.size()<<endl;

   return 0;
}

Read: Intro to Sequence Containers in C++

The vector Sequence Container

The vector implementation is nothing but dynamic arrays. They have the same data structure of contiguous memory location. Although it is implemented with arrays at the core, which is static in nature, the vibe of dynamism is in its ability to resize itself automatically as the number of elements inserted exceeds its initial capacity. The container implements the accommodation logic and allocates another chunk of memory. This means that the container has a built-in capability of storage management. We can use iterators to access and traverse the elements all throughout the store. The elements are inserted at the end of the container; therefore, any lack of space found during insertion leads to the extension of the container from the end. But, note that automatic resizing does not occur during element removal. Although there is a method called shrink_to_fit() to explicitly request for shrinking, the request may not be granted.

A Quick Example of a vector Sequence Container in C++

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

int main()
{
   vector<string> planets;
   planets.push_back("Mercury");
   planets.push_back("Venus");
   planets.push_back("Earth");
   planets.push_back("Mars");
   planets.push_back("Jupiter");

   cout<<"Size = "<<planets.size()<<endl;
   cout<<"Capacity = "<<planets.capacity()<<endl;

   for(auto iter = planets.cbegin(); iter != planets.cend();
         iter++)
      cout<<*iter<<endl;

   return 0;
}

Resizing a vector is a time-space tradeoff and is not very clear exactly how C++ does it internally. Also note that different versions of the C++ compiler supply a slightly different version of the container classes. There can be some addition to the functions the sequence container supports. But, the core functionalities are more or less the same. With C++11, it is possible for vector or deque to release unneeded memory back to the system with the help of a function called shrink_to_fit(). Note that this is a request and C++ may ignore it in favor of implementation-specific optimization.

The deque Sequence Container

Understand that the array sequence container cannot expand and has one-way entry; the vector sequence container can expand but cannot contract; it also has one-way entry. But, the deque sequence container although uses vector as its core data structure implementation and can be expanded and contracted with insertion and deletion at both ends. They are more efficient than vectors but, unlike vectors, contiguous memory allocation is not guaranteed. The ‘deque’ essentially means double-ended-queue and works in a similar fashion as queues; in other words, a FIFO (first-in-first-out) manner. Double ended means that the FIFO can occur at both ends (front and rear).

A Quick Example of a deque Sequence Container in C++

#include <iostream>
#include <iomanip>
#include <deque>

using namespace std;

void print(deque<int> dq)
{
   deque <int> :: iterator iter;
   for (iter = dq.begin(); iter != dq.end(); ++iter)
      cout<<*iter<<' ';
   cout<<endl;
}

int main()
{
   deque<int> nums;
   nums.push_back(10);
   nums.push_front(1);
   nums.push_back(9);
   nums.push_front(2);
   nums.push_back(8);
   nums.push_front(3);
   nums.push_back(7);
   nums.push_front(4);
   nums.push_back(6);
   nums.push_front(5);

   cout<<"Size = "<<nums.size()<<endl;
   cout<<"deque contents"<<endl;
   print(nums);
   cout<<"After popping an element from the front"<<endl;
   nums.pop_front();
   print(nums);
   cout<<"After popping an element from the back"<<endl;
   nums.pop_back();
   print(nums);

   return 0;
}

The forward_list Sequence Container

The forward_list is implemented as a singly linked-list where each node contains a data element and a reference pointer to point to the next element in the list. Due to its forward moving structure, each keeps information about its next element and hence traversal can be done in forward direction only. The container is useful for algorithms that require insertion, deletion, and forward iteration of elements. Because it is implemented with linked-list, it is completely dynamic in nature and the size of the list is immaterial.

A Quick Example of a forward_list Sequence Container in C++

#include <iostream>
#include <iomanip>
#include <forward_list>

using namespace std;

void print(forward_list<int> flist)
{
   forward_list <int> :: iterator iter;
   for (iter = flist.begin(); iter != flist.end(); ++iter)
      cout<<*iter<<' ';
   cout<<endl;
}

int main()
{
   forward_list<int> nums;

   nums.assign({1,2,3,4,5,6,7,8,9});

   cout<<"forward_list contents"<<endl;
   print(nums);
   nums.merge({11,22,33,44});
   cout<<"After merging new element in the list"<<endl;
   print(nums);

   return 0;
}

The list Sequence Container

Similar to forward_list, the list is also non-contiguous memory allocation, but is implemented as a doubly linked-list. This means that in the list container both forward and backward traversal is possible. It also has a sort function to arrange elements in ascending order and invokes it after merging new elements into the list. The main operational difference between list and forward_list is that it supports traversal both way, whereas another supports forward traversal only. Compared to static sequence containers, both forward_list and list are slow to find a location in the list but, once found, insertion and deletion is pretty fast.

A Quick Example of the list Sequence Container in C++

#include <iostream>
#include <iomanip>
#include <list>

using namespace std;

void print(list<int> lst)
{
   list <int> :: iterator iter;
   for (iter = lst.begin(); iter != lst.end(); ++iter)
      cout<<*iter<<' ';
   cout<<endl;
}

int main()
{
   list<int> nums;

   nums.assign({1,2,3,4,5,6,7,8,9});

   cout<<"list contents"<<endl;
   print(nums);
   nums.merge({11,22,33,44});
   cout<<"After merging new element in the list"<<endl;
   print(nums);

   return 0;
}

Conclusion

Every container has a type called iterator. The iterator is nothing but a pointer to the elements of the container. It can be incremented or decremented to traverse through all the elements and also can be used to select one element from the container. The primary goal of the two types of sequence container implementation, be it array or linked-list, is to provide the maximum freedom in the design of an individual container, while at the same time allowing containers to present a common interface to users. The sequence containers comply with some common property: they are sequential in nature, which means that the elements can be accessed sequentially. Secondly, they have similar interfaces with many common functions.

Check out this C++ Beginners Course!

References

  • Bjarne Stroustrup. The C++ Programming Language. 3rd ed.
  • Deitel, Paul J, and Harvey M Deitel. C++ How to Program, 9th ed.

The post An Introduction to Sequence Containers in C++ appeared first on CodeGuru.

]]>
C++ Classes and Objects Overview https://www.codeguru.com/cplusplus/c-plus-plus-classes-objects/ Fri, 17 Dec 2021 05:38:31 +0000 https://www.codeguru.com/?p=18808   Object-oriented programming (OOP) is a principle of programming centered around representing real-world objects as part of code. This is done specifically using two concepts: classes and objects. What are Classes and Objects in C++? Classes, user-defined data types, are templates from which objects can be created. In turn, an object is an instance of […]

The post C++ Classes and Objects Overview appeared first on CodeGuru.

]]>
 

C++ OOP tutorial

Object-oriented programming (OOP) is a principle of programming centered around representing real-world objects as part of code. This is done specifically using two concepts: classes and objects.

What are Classes and Objects in C++?

Classes, user-defined data types, are templates from which objects can be created. In turn, an object is an instance of a class. You can say that objects are the physical entity used in a running program for a specific purpose, whereas the class is the logical thing used to bind data and functions. A class can be thought of as the blueprint for an object.

For example, let’s consider the class Student. There may be many students with different names, taking different subjects, but they will share overlapping properties, such as a First Name, Last Name, a GPA, and so on. In this case, Student is the class and First Name, Last Name, GPA, and so forth are their properties.

We can use Object-oriented programming to conceptualize students, food, cars, and more real-life things and represent them to be manipulated in code. The way we do this is through Object-oriented programming principles. Among other languages, the modern C++ language uses these concepts as building blocks for its own object-oriented feature.

A cross-platform, general-purpose programming language, C++ was created by Bjarne Stroustrup as an extension of the C language. Essentially starting out as “C with Classes,” the language has since expanded to include generic, object-oriented, and functional features as well as being able to facilitate low-level memory manipulation.

The main purpose of C++ is to add object orientation to C programming and classes are the central feature that allows for object-oriented programming.

Read: An Object-oriented Programming Primer

Classes in C++

A Class is the building block of object-oriented programming and we start creating a class in C++ by using the keyword class, followed by a user-defined name. The body of the class that follows is defined within a set of curly brackets { } and a semicolon ; at the end to signify it is terminated. Here is an example of how to create a class in C++:

class Student {
	Access modifier:

	Data Members/variables;

	Member Functions() {}
};

By default, a class’s modifier is private, meaning that the data members made here are only accessible within this class. In order to use the data members and functions outside the class, you will need to make them public by using the public: modifier.

class Student {
public:

	Data Members/variables;

	Member Functions() {}
};

Data members you can declare are variables you want to be associated with your class; attributes for an object you perceive need to be manipulated:

class Student {
public:

	string name;
	float gpa;
	list classes;

	Member Functions() {}
};

Read: Creating Classes and Objects in Visual Basic

Objects in C++

Next, you will want to define the object. After declaring the class, only the specifications of an object are defined. No memory or storage is used at this point. In order to use the data and gain access to the class defined functions that manipulate that data you will need to start creating objects.

You start by declaring the type of object you want to create, then the class, followed by a name for that object. You can follow this up by building this first object up with its associated attributes. After that, you can use those attributes like any other variable, starting with printing them out, as in the following example:

int main {
Student Student01;
Student01.name = “William”
Student01.gpa = 2.2
Student01.classes = {“Math”, “Science”, “History”, “English”}

cout << “Name: “ << Student01.name << end1;
cout << “GPA: “ << Student01.gpa << end1;
cout << “Classes: “<< end1;
for (string classtitles : Student01.classes){
	cout << classtitles << end1;
}
}

Now we have our first object. If we want to create more, then we will need to repeat the process again for any number of unique students. But this will surely go against several coding principles, especially the one about keeping things simple. In order not to inundate yourself with repetitive and bloated code, you will want to consider constructors and class methods.

Constructors and Class Methods in C++

A constructor is a special method that will be called by the compiler every time an object is being created from a specific class. There are two conditions for forming a constructor; first, it must have the same name as the class it is in, and second, it must not have a return type.

class Student {
public:

	string name;
	float gpa;
	list classes;

	//Parameterized constructor
	Student(string Name, float GPA) {
		name = Name;
		gpa = GPA;
}
};

Now we can simplify our earlier code snippet:

int main {
Student Student01(“William”, “2.2”);
Student01.classes = {“Math”, “Science”, “History”, “English”}

cout << “Name: “ << Student01.name << end1;
cout << “GPA: “ << Student01.gpa << end1;
cout << “Classes: “<< end1;
for (string classtitles : Student01.classes){
	cout << classtitles << end1;
}
}

This is an example of a parameterized constructor, which takes in attributes as variables and helps construct an object. There are also default constructors and copy constructors.

Read: Explore Constructors and Destructors in C++

A default constructor is a constructor that does not take in any parameters and resorts to prepared values for an object when this constructor is called. When no constructor is made, or one is made with no body, the compiler will provide a default constructor implicitly. Note that a user can make their own default constructor with values they can set as default as well.

class Student {
public:

	string name;
	float gpa;
	list classes;

	//default constructor
	Student() {
		name = New Student;
		gpa = 0;
	}

	//Parameterized constructor
	Student(string Name, float GPA) {
		name = Name;
		gpa = GPA;
}
};

A copy constructor is a method that initializes a new object using another object of the same class.

class Student {
public:

	string name;
	float gpa;
	list classes;

	//default constructor
	Student() {
		name = New Student;
		gpa = 0;
	}

	//Parameterized constructor
	Student(string Name, float GPA) {
		name = Name;
		gpa = GPA;
}

//Copy constructor
Student(const Student &Student01) {
	name = Student01.name;
	gpa = Student01.gpa;
}
};

In the same way, one could create class methods that take in attributes and set in parameters for an object or produce more data:

class Student {
public:

	string name;
	float gpa;
	list classes;

	//class functions declaration
	float getGPA(float GPA);
	float setGPA(float GPA);

	//Parameterized constructor
	Student(string Name, float GPA) {
		name = Name;
		gpa = GPA;
}

};

//class functions
float getGPA(void) {
	return gpa
}
void setGPA(float GPA) {
	gpa = GPA
}

Other Features of C++ Object-oriented Programming

One more instance member function to know about is the destructor, which is a method that is called automatically to destroy an object that was made. The destructor’s properties include not having arguments, no return type, they cannot be declared static or const, and more. What happens when this method is called is that the program ends, the function ends, a block holding local variables ends, and a delete operator is called. Destructors have the same name as the class but are preceded by a tilde (~). They do not take any argument and do not return anything.

Languages with Object-oriented tendencies can feature a concept called multiple inheritance, which is also a feature within the C++ language. Multiple Inheritance itself is the way in which a class can inherit attributes from more than one parent class. Developers can use this characteristic of C++ to compartmentalize memory and make more classes less obtrusive of a job.

Conclusion of C++ Objects and Classes Tutorial

C++ is a versatile and powerful general-purpose language designed for system programming and embedded software, for software with constrained resources as well as large systems, with efficiency, performance, and flexibility as its features. You can find C++ in many areas, as it’s been useful in the development of many low-level applications, such as drivers and kernels, as well some higher-level applications, like desktop applications, servers, video games, and more.

The object-orientation of C++ allows for this versatility, proving that it can be a true asset in a developer’s toolset.

Read more C++ programming tutorials and how-tos.

Check out this C++ Beginners Course!

The post C++ Classes and Objects Overview appeared first on CodeGuru.

]]>
Pointers in C: A Beginner’s Guide https://www.codeguru.com/cplusplus/pointers-in-c/ Tue, 28 Sep 2021 16:01:51 +0000 https://www.codeguru.com/?p=18575 A pointer is a variable used to store a memory address. Pointers enable you to pass values by reference (modify values in memory) and to work with dynamic data structures such as queues and stacks. In this article, developers will learn how they can define pointers and what operations you can perform with them. Creating […]

The post Pointers in C: A Beginner’s Guide appeared first on CodeGuru.

]]>
A pointer is a variable used to store a memory address. Pointers enable you to pass values by reference (modify values in memory) and to work with dynamic data structures such as queues and stacks.

In this article, developers will learn how they can define pointers and what operations you can perform with them.

Creating Pointers in C

You can create pointers to variables of any data type. To create a pointer, state the data type followed by an asterisk (*) and the pointer name, as in the following example:

int *countPtr;

You can also define a pointer by placing the asterisk in front of the data type. The first syntax is preferred, though:

int* countPtr;

Unlike when defining normal variables, the * operator does not distribute to all the pointer variables. Observe the following C code:

int *b, y;

In the above statement, only the variable b is a pointer of type int. Meanwhile, y is just a variable of type int.

If you want to declare multiple pointers in the same statement, then you need to add an asterisk before each pointer variable, as shown below:

int *bPtr, *yPtr ;

How to Initialize Pointers in C

Pointers must always be initialized when defined. You can initialize a pointer with NULL, 0 or an address. Initializing a pointer to NULL is the same as initializing it to 0 (zero).

A pointer initialized to any of these two values (NULL or 0) points to nothing.

The third way to initialize a pointer is to assign an address to it. The reference operator (&) is used to assign a memory address to a pointer. It’s a unary operator that takes in a variable as its operand. Here it is in use:

int y;
yPtr = &y;

It is important for you to note that a constant or an expression can’t be used as an operand to the & operator.

As mentioned earlier, pointers store memory addresses. If you want to get the memory address which your pointer is storing, then you would use the dereferencing operator (*).

This operator will return a hexadecimal value that indicates the memory location which your pointer is storing. See the example below:

# include  

int y = 7;
int z;

int yPtr = &y;
int zPtr = &z;

printf("The pointer yPtr is storing the address %p: " , &y); 
printf("\n The value stored by *yPtr is: ", *yPtr);

The code example above demonstrates how you can use the address operator and the dereferencing operator.

Other Pointer Types in C

Apart from the null pointer, there are also other pointer types that are worth mentioning. We discuss them below.

Void Pointer in C

The void pointer is a pointer that can store an address of any data type. It is also known as a generic pointer.

To define a void pointer in C, use the keyword void in your pointer declaration. Here is some example code:

int main() 
{
  void  *aPtr;
  void  *bPtr;
  
  int a = 6;
  char b = 'G';

  aPtr = &a; // aPtr stores a pointer to an integer 
  bPtr = &b; // bPtr stores a pointer to a character 
}

Wild Pointer in C

A wild pointer is a pointer that has not yet been initialized. This pointer points to an arbitrary location in memory. You should generally never use such a pointer. Doing so could crash a running program in memory. That being said, here is how you use wild pointers:

float  *Yptr; // this a wild pointer. Don't use it until you initialize it

Passing Values by Reference in C

There are two ways in which you can pass arguments to a function. You can either pass-by-value or pass-by-reference.

Pass-by-value means that the value of the argument is passed to the function while pass-by-reference means that a pointer to the argument is passed.

By default, all arguments are passed by value in the C language. Pass-by-value first makes a copy of the argument and then passes on this copy to the function. This introduces overheads in processing and also leads to high memory usage.

Pointers can be used to overcome this challenge since they work directly with variables in their addresses.

The code example below shows how you can get the square of an integer using pass-by-value and pass-by-reference:

#include 

void SquareByValue (int p){
p*p; }

void SquareByReference (int *qPtr){
*qPtr * *qPtr;  }

int main (){

int a = 4;
int b = 6;
}

C Pointers

Unlike Java and Python, C gives you the option to directly work with memory addresses for your program.

As you must be aware by now: “With great power comes great responsibility.” If you inappropriately allocate memory addresses, you could end up crashing programs running on your computer.

Pointers should be used with care. In particular, you should avoid wild pointers.

Read: Data Types, Variables, and Constants in C++.

The post Pointers in C: A Beginner’s Guide appeared first on CodeGuru.

]]>
Simple Data Input and Output Operators in C++ https://www.codeguru.com/cplusplus/data-input-output-operators-c/ Wed, 22 Sep 2021 02:43:58 +0000 https://www.codeguru.com/?p=18564 In C++, the “<<” operator is used to redirect to the standard input-output object. During redirection, the “\n” definition is used to jump to the beginning of the next line after a line is printed. The word “cin” is used together with the “>>” operator when entering data from the keyboard. In order to be […]

The post Simple Data Input and Output Operators in C++ appeared first on CodeGuru.

]]>
In C++, the “<<” operator is used to redirect to the standard input-output object. During redirection, the “\n” definition is used to jump to the beginning of the next line after a line is printed. The word “cin” is used together with the “>>” operator when entering data from the keyboard.

In order to be able to allow for input and output, the iostream file containing the relevant libraries must be included in the program, as shown below:

#include 
using namespace std;

C++ Operators

Symbols used to change data by performing arithmetic operations on a set of data, to obtain a new set of data from two existing pieces of data, to compare more than one piece of data, or to perform logical operations on the data are called operators.

In the following section, we will learn about some of the different C++ operators and how to use them. We begin with the assignment operator, which is represented by the equal sign or =.

Assignment Operator (=) in C++

The = operator is used when assigning any value to a variable. Here is an example of how to use the assignment operator = in C++:

int num = 12;
char letter = 'n';

Arithmetic Operators in C++

Operators used for performing mathematical operations in C++ are known as arithmetic operators. These operators work – mostly – in the same way that the math operators you learned in school work. For example, the + operator – or addition operator – is used to add two or more numbers to one another.

The C++ arithmetic operators include:

  • Addition: This operator is used to perform addition. It is represented by the + symbol.
  • Subtraction: This operator is used to perform subtraction. It is represented by the symbol.
  • Multiplication: This operator is used to perform multiplication. It is represented by the asterisk or * symbol.
  • Division: This operator is used to perform division. It is represented by the forward-slash or / symbol.
  • Modulo: This operator is used to return the remainder of a division. It is represented by the percent or % symbol.

Below is a list of examples showing how to use the various mathematical operators C++ has to offer. Feel free to try the code our in your integrated development environment (IDE) or code editor to better understand their use:

C++ Addition Operator Example:

#include 
using namespace std;

// This program adds two numeric values
// and displays the result.

int main() {
  int num1 = 120;
  int num2 = 300;
  int Sum;

  Sum = num1 + num2;

  cout << "Total: " << Sum << "\n";

return 0;
}

Running this code results in the following output:

Total: 420

Here is an example of how to use the C++ multiplication * operator to find the area of a circle:

C++ Multiplication Example:

#include 
using namespace std;

// Area of the Circle

int main() {
  double pi = 3.1415;
  double r = 13;
  double area;

  cout << "Area of the Circle" << "\n";
  cout << "--------------" << "\n";

  area = pi * r * r;
 
  cout << area << " cm2" << "\n";

return 0;
}

This code results in the following output:

Area of the Circle
--------------
530.914 cm2

This code example shows how to use multiple C++ mathematical operators:

#include 
using namespace std;

int main() {

  int num1 = 6, num2 = 3;
  cout << "sum of two numbers = " << num1 + num2 << endl;
  cout << "subtraction of two numbers = " << num1 - num2 << endl;
  cout << "product of two numbers = " << num1 * num2 << endl;
  cout << "division of two numbers = " << num1 / num2 << endl;

return 0;
}

Once more, the output of running this code is:

sum of two numbers = 9
subtraction of two numbers = 3
product of two numbers = 18
division of two numbers = 2

Modular Arithmetic Operator (%) in C++

As we all know from mathematics, when the first number is divided by the second number, the remainder is the mod value. When you want to return the modulo – or remainder of a division – in C++, you can do so in the following manner:

#include 
using namespace std;

int main() {

  int x = 8 ,y = 4 ,z = 3;
  int mod1 = x%y;
  int mod2 = x%z;
  int mod3 = y%z;

  cout << "mod1 = " << mod1 << endl;
  cout << "mod2 = " << mod2 << endl;
  cout << "mod3 = " << mod3 << endl;

return 0;
}

The above code sample results in the following output when you run it in your code editor or IDE:

mod1 = 0
mod2 = 2
mod3 = 1

Increment and Decrease Operators in C++

The ++ operator increments the value of the adjacent variable by one; the operator decrements it by one. The meaning of these operators changes if they are placed to the left or right of the variable.

The following example show what happens if we use the increment ++ operator to the left of the variable:

a = ++b

The increment operator first increments the value of b by one and then assigns it to the variable a. In this situation, the value of the a and b variables will be the same.

On the other hand, if we use the increment operator to the right of the variable, as in this example:

a = b++

The increment operator first assigns the value of b to a, then increments b by one. In this situation, the value of b is one more than the value of a.

Let’s summarize the use of the increment and decrement operators in a table:

C++ Increment Decrement Operators

Here are some examples further showing how to use increment and decrement operators in C++:

//Multiplication of one minus of the entered numbers
#include 
using namespace std;
 
int main() {
  int a,b;
  cout << "Enter first number: "; cin >> a;
 
  cout << "Enter second number: "; cin >> b; --a; --b;
 
  cout << "total = " << a*b << endl;

return 0;
}

This results in the following output:

Enter first number: 3
Enter second number: 5
total = 8

Example 2:

//Using the increment operator
#include 
using namespace std;

int main() {
  int a=50;
  int b=30;
  cout << "a= " << a++ << "\n";
  cout << "a= " << a << "\n";
  cout << "b= " << ++b <<"\n";
return 0;
}

Again, the result of running this code results in the follow output:

a= 50
a= 51
b= 31

Example 3:

//Using the increment operator 2
#include 
using namespace std;
int main() {
int counter; int a;
counter=5; a=0;
a=counter++;
cout << "a= "<< a++ << "\n";
cout << "counter= " << counter << "\n";
cout <<"--------"<<"\n";
counter=5; a=0;
a=++counter;
cout << "a= " << ++a << "\n";
cout << "counter= " << counter<< "\n";
return 0; }

Running this code in your code editor results in:

a= 5
counter= 6
--------
a= 7
counter= 6

Arithmetic Assignment Operators in C++

In C++, some arithmetic operations can also be expressed in a different form, known as abbreviated.

C++ Math Operator

Comparison Operators in C++

Operators used to compare two numeric values or two characters are known as comparison operators. The if statement is used for comparison as well. If the result of the comparison is “true”, the line following this statement is processed; if “not true” – or false -, the line after the else statement is processed.

Here is a list of the available comparison operators in C++:

  • Greater than: Used to test if a value is greater than another value. It is represented by the > symbol.
  • Less than: Used to test if a value is less than another value. It is represented by the < symbol.
  • Greater than or Equal to: Used to test if a value is either greater than OR equal to another value. It is represented by the >= symbol.
  • Less than or Equal to: Used to test if a value is either less than OR equal to another value. It is represented by the <= symbol.
  • Equal to: Used to test if a value is equal to another value. Represented by two equal symbols or ==.
  • Not Equal: Used to test if a value is not equal to another value. Results in true if so. Represented by the !=.

Here are some examples of how to use comparison operators in C++

Comparison Operator Example 1

//Comparison Operators
#include 
using namespace std;

int main() {
int num;
cout << "Enter a number:"; cin >> num;
if (num<0)
cout << "Entered a negative number: " << num<< "\n";

else
cout << "Entered a positive number: " << num << "\n";

return 0;
}

Here is the output of this code:

Enter a number:-10
Entered a negative number: -10

 
Enter a number:5
Entered a positive number: 5

Comparison Operator Example 2

#include 
using namespace std;
int main() {
bool a=(6<3); bool b=(5>8);
bool c=(10<=10); bool d=(12>=15);
bool e=(1==1);
bool f=(0!=0);
cout << "a value= " << a << endl;
cout << "b value= " << b << endl;
cout << "c value= " << c << endl;
cout << "d value= " << d << endl;
cout << "e value= " << e << endl;
cout << "f value= " << f << endl;
return 0;
}

Here is the output of this example:

a value= 0
b value= 0
c value= 1
d value= 0
e value= 1
f value= 0

As you probably know, 0’s represent “not true” and 1’s represent “true”. Using the bool method, we are able to achieve these results.

Logical Operators in C++

Logical operators are used to test two or more conditions together. In this case, two or more conditions are evaluated together considering their truth values.

C++ Logical Operators

Below you will find some programming examples of C++ logical operators.

Logical Operator Example

//logical operators
#include 
using namespace std;

int main() {
int num1,num2;

cout << "Enter first number: "; cin >> num1;
 
cout << "Enter second number: "; cin >> num2;

if (num1>0 && num2>0)
cout << "Both numbers are positive";

else cout << "At least one of the numbers is negative.";
return 0;
}

The result of this code? See below:

 

Enter first number: -5
Enter second number: 15
At least one of the numbers is negative.

Special Purpose Ternary Operator ( ? : ) in C++

The special ternary operator performs in the same manner as the if structure. Its usage is as follows:

 ?  :

If the condition is true, the expression to the left of the : sign is valid, and if the condition is not true, the expression to the right of the : sign is valid.

Here is an example of the ternary operator in C++ being used:

#include 
using namespace std;
int main() {
int a=10, b=5, c=25, d=15, e, f;
e=a>b ? a:c;
f=c

This code results in the following output:

e value= 10
f value= 13

Priority Order of Transactions and Order of Precedence

Just like in mathematics, most programming languages have a sequence of operations or order of precedence. In order for C++ to execute operations in an orderly manner, a priority order is defined for each operation. According to this order, operations in parentheses are performed first, and, finally, the sequence of operations is concluded with the equals operator.

Operations with the same priority are in order of priority from left to right.

You can examine the table below for the order of priority:

C++ Operator Precedence

C++ Operator Precedence

C++ Operator Precedence

You learned about operator operations and how they are used in C++. Based on the practices we provide, you can code your own simple programs, so you will repeat and learn the subject better. Please do not try to memorize them. This will both delay your learning and cause confusion. Instead, try to practice by writing a lot of software projects and C++ code.

Read more C++ programming tutorials.

Check out this C++ Beginners Course!

The post Simple Data Input and Output Operators in C++ appeared first on CodeGuru.

]]>
C++ Data Types & Variables for Beginners https://www.codeguru.com/cplusplus/cplusplus-data-types-variables-for-beginners/ Wed, 15 Sep 2021 16:09:45 +0000 https://www.codeguru.com/?p=18551 In this programming tutorial, developers will learn how to work with variables, data types, and constants in the C++ programming language. If you are a new C++ developer, you may want to read the first part of this ongoing series about C++ software development – C++ for beginners. We will start with variables and then […]

The post C++ Data Types & Variables for Beginners appeared first on CodeGuru.

]]>
C++ Variables and Data Types

In this programming tutorial, developers will learn how to work with variables, data types, and constants in the C++ programming language. If you are a new C++ developer, you may want to read the first part of this ongoing series about C++ software development – C++ for beginners.

We will start with variables and then work our way through C++ data types.

Every variable used in C++ must be declared and introduced to the program before they are able to be used. During this declaration, the data type of the variable must also be determined.

Below is an example of basic usage of a variable in C++:

<datatype> <name of variable>;

Read: Simple Data Input and Output Operators in C++

What Are C++ Data Types?

The basic data types commonly used to define integers in C++ include:

  • int
  • long
  • short

The int and long data types occupy 4 bytes of memory, and the short data types occupy 2 bytes.

The basic data types commonly used to define floating-point numbers or decimal numbers include:

  • double
  • long double
  • float

The double and long double data types occupy 8 bytes of memory, while the float data types occupy 4 bytes.

The following data type is used to identify an alphabetic character or strings of characters:

  • char

Each character occupies 1 byte of memory.

You can review the table below for the data types used in C++.

C++ Data Types

Read: Productivity Tools for .NET Developers

How Do You Declare Variable Data Types in C++?

To declare the data type of the variable to be used in C++, a definition must be made, as follows:

<datatype> <name of variable>;

Here is how you declare a variable data type in C++ code:

int age;
float price;
char letter;

It is possible to change the content of a variable by assigning a specific value anywhere in the program. Often, however, the data type of the variable is determined from the outset, while it is desirable to have a value as well.

 <datatype> <name of variable> = <value>;

Here is how that would look in code:

int age = 26; 
float price = 32.95; 
char letter = "f"; 

If we are going to use more than one variable in our program, we can define these variables by writing them side by side, provided that they are of the same type. Here is how you declare multiple variables in C++:

int num1, num2; 
int num1=13, num2=14; 

Lines where the variable data type is declared must end with.“;”

Code:
#include 
using namespace std;

int main() 
{
   int smallest=10; 
   int largest=100; 

   cout <<"Smallest Number: " << smallest << "\n"; 
   cout <<"Largest Number: " << largest << "\n";
   return 0; 
}

Running this code in your integrated development environment (IDE) or code editor would result in the following output:

Smallest Number: 10
Largest Number: 100

Read: How to Operate on Strings in C++

C++ Variable Naming Conventions

There are some important rules to consider when defining a variable name in C++:

  • C++ is case-sensitive. For example, here is how you name variables in C++:
char letter; 
char Letter; 
char LETTER;

All three of the above statements describe different variables. Therefore, we must be very careful when using lowercase and uppercase letters in variable names.

  • No symbols should be used in variable names, except for the numbers, lowercase alphabetic characters, and uppercase alphabetic characters in the table above. However, the underscore (_) character is excluded from this scope and can be used in variable names.
  • Variable names must begin with a letter or an underscore (_) character, never with a number, symbol, or symbol.
int sayi;
int _sayi;
  • The name of a variable can be up to 255 characters.
  • Space characters should not be used in variable names. However, the underscore (_) character can be used instead of a space.
int summer_of_sixtynine;
  • C++-specific keywords cannot be used in variable names. These words are given in the table below:

C++ Reserved Keywords

Read: What Are References in C++

What are Variables in C++?

Variable definitions can be made for different purposes in C++. Although various types of variables are used in C++ programs, for now, we will consider two types of variables that are frequently used: local variables and global variables.

Local Variables in C++

If there is more than one function in the program, local variables are the type of variable that can only be valid in the function it is defined in. Such variables must be enclosed in curly braces { } that indicate function boundaries.

Global Variables in C++

Global variables are the variable type that can be valid in all functions in the program. Such variables must be placed outside of the curly braces { } that specify function boundaries.

Static Variables in C++

When a locally defined variable in a function is required to remain constant and not change if the function is called repeatedly as long as the program is running, that variable should be defined as a static variable.

What are Constants in C++?

Constants are program components whose value does not change from the beginning to the end of the program. Constants with the following data types can be used in C++:

  • Integer Constants
  • Decimal Constants
  • Character Constants
  • String Constants

We discuss each type of C++ constant below.

Integer Constants in C++

There are three types of integer constants: ‘int‘ (integer), ‘short‘ (short integer), and ‘long‘ (long integer). Let’s take 1995 as an example and explain the job of defining the type of an integer in this example.

To indicate which type a constant belongs to, a character is added to the end of that constant to indicate its type. If a numeric expression does not have any characters at the end, the type of that expression is ‘int‘. In this case, the expression 1995 in our example is an integer of type ‘int‘. To designate this expression as type ‘long‘ we need to append an l or L character: 1995l or 1995L. In that way, the expression now belongs to type ‘long’ and not type ‘int‘.

Also, integers that cross the ‘int‘ type limits in the flow of the program are automatically converted to ‘long’, even if they do not have a trailing l or L suffix.

There is a special case for the ‘short‘ type. When calculating the value of an expression, it is treated like ‘int‘, even though it belongs to type ‘short‘. In this case, we can say that there is no constant of type ‘short‘, because constants within the bounds of ‘short‘ are considered to be type ‘int‘ by C++.

Read: C++ Classes and Objects Overview

Decimal Constants in C++

There are three types of decimal constants in C++: ‘float‘ (floating decimal), ‘double‘ (double decimal), and ‘long double‘ (long decimal). Let’s take the expression 1881.1938 as an example and explain the job of defining the type of an integer in this example.

If a decimal constant does not have any characters at the end, the type of that expression is considered ‘double‘. In this case, 1881.1938 in our example is a decimal constant of type ‘double‘. To designate this expression as a type of ‘float‘, we need to append the f or F character: 1881.1938f or 1881.1938F. In this way, the expression no longer belongs to the ‘double‘ type but of the ‘float‘ type instead.

Although not often used, to specify a decimal constant of type ‘long double‘, we must append the character l or L: 1881.1938l or 1881.1938L.

Character Constants in C++

We know that type ‘char‘ takes a value between -128 and +127 or 0 and +255. Well, since these constants are named ‘characters‘ and have an alphabetic nature, why are we still talking about numerical expressions?

Because every character used in C++ has a numeric equivalent in the ASCII (American Standard Code for Information Interchange) table, and these numbers, in which the character constants are kept within the specified ranges, are the ASCII equivalents of the characters used. In other words; when we talk about 97 as the character constant, we are actually talking about the character ‘a’, which is the ASCII table equivalent of 97.

When using character constants, we can use the numeric equivalents of the characters. Of course, the commonly preferred usage in C++ is to use the characters themselves. However, when we are going to use the characters themselves, we must enclose these characters in single quotes (‘).

In the following lines, two variables of type char are defined and the constants 103 and g are assigned to these variables, respectively.

char character1=103; 
char character2='g';  

Since the numeric equivalent of the ‘g’ character in the ASCII table is 103, these two lines actually mean the same thing. However, pay special attention to the fact that the ‘g’ character is written in single quotation marks.

Read: Visit our C++ Forum for More Discussions on C++ Programming

String Constants in C++

string (character) literals consist of sequentially ordered strings of character literals. In C++, every expression enclosed in double-quotes () is a constant of type string. Consider the following examples:

  • “Fatih”
  • “1995”
  • “1920.1923”
  • “Harvard University”

As you can see, numeric expressions enclosed in double quotes are now a ‘string‘ constant. We can no longer do numerical operations such as addition and subtraction with them.

Actually, there is no type named string in C++. The string type occurs when the compiler treats multiple character constants as a string of characters. Accordingly, the expression “Fatih” would actually work like this:

'F' 'a' 't' 'i' 'h'

The compiler treats all these characters as a string and puts them together by adding the ‘/0’ character to the end.

Constants are defined with the word const in C++, and the following definitions are made to declare the data type of the invariant to be used:

int const constant name = value;
char const constant name = 'value';

Consider the following code:

#include 
using namespace std;

int const age = 15;
char const gender = 'M';

int main() 
{
   cout << " Age: " << age <<"\n";
   cout << " Gender: " << gender <<"\n";
  
   return 0; 
} 

Running this code in your code editor would result in the following output:

Age: 15
Gender: M

Type Conversion in C++

Variables or constants in our programs can be of different types. If this is the case, it is important what type of calculation result will be in our mathematical operations. Therefore, type conversion must be done to avoid an error.

#include 
using namespace std;

int main(){

  int num=9; 
  float a,b,c; 

  a=num/4; 
  b=num/4.0; 
  c=(float)num/4; 

  cout << "a value= " << a << endl; 
  cout << "b value= " << b << endl; 
  cout << "c value= " << c << endl; 

return 0; }

The output of this code is:

a value= 2
b value= 2.25
c value= 2.25

In the above application:

In the first operation, we divide the variable named num by an integer value; The decimal point is ignored and the result is assigned to variable a as an integer.

In the second operation, we divide the variable named num, which is an integer, by a decimal value; The part after the comma is taken into account and the result is assigned to the variable b as a decimal value.

IIn the third operation, we first convert the variable named num, which is an integer, into a variable of type float. Next, we divide the variable that is now float by an integer value; the result is assigned as a decimal value to the variable c.

C++ Data Types Tutorial Conclusion

If you have come this far, congratulations. You are now familiar with the data types, constants, and variables of the C++ programming language. C++ is a language with so many features to explore. So never forget to learn, wonder and research.

It is a difficult language as well as a fun one. But if you enjoy it, C++ will give you more.

Read more C++ programming tutorials and developer guides.

Check out this C++ Beginners Course!

The post C++ Data Types & Variables for Beginners appeared first on CodeGuru.

]]>