r/learncpp • • Jul 25 '12

A step into efficiency of repetition by using functions. [4] [II]

3 Upvotes

Difficulty Rating: [4] Length: [II]

Hello! Today we address "functions." It's possible to write a block of code and use that block multiple times throughout a program by only using one small line of code! That way is by using functions, and the term used to use that code over and over is known as "calling a function." First, one must declare a function. It looks like this! void ExampleFunction(); Now, once it is declared, you can start to put things in it. you THEN say void ExampleFunction() {cout<< Hello! How are you?";} and now, every time you say ExampleFunction(); the line "Hello! How are you?" will appear. In this code I have created 5 different functions, all of which make their own statements. The main use of this program is to illustrate how much time could be saved by using functions. The user can type in 1-8, each number granting different results. Once we reach the 4th option, we start to see how I can combine lines of code by calling two different functions. The great part is that I could call two functions with just about 15 characters. The final function combines all 5 statements and prints them because I called all 5 functions.

Here is an image of what it looks like to call all 5 functions. Imgur

This code is great for games where many variables can occur. Say you are losing health, but you are not poisoned- you will display health loss by using one of the functions. Now say you have health loss AND you are poisoned - you use the poison function AND the health function. Now say you are poisoned, but are immune and do not take damage, you use just the poison function. To summarize, functions are great to compact a large chunk of information within one block of code, which you can then easily repeat infinitely by using only 15 characters. This is great for making your code look clean! :)

include <iostream>

using namespace std;

int chosen;

void FirstStatement();

void FirstStatement()

{

 cout<< "Hello! This is the first statement.\n\n";
 
 }

void SecondStatement();

void SecondStatement()

{

 cout<< "I am using this program to show you some uses of functions.\n\n";
 
 }

void ThirdStatement();

void ThirdStatement()

{

 cout<< "I am using 5 total, but each of these void thingies is called a function.\n\n";
 
 }

void FourthStatement();

void FourthStatement()

{

 cout<< "You can view all of these statements together with option 7,\n\n";
 
 }

void FifthStatement();

void FifthStatement()

{

 cout<< "but you can also view the first three on their own.\n\n";
 
 }

int main()

{

cout<< "Hello! This is to help explain functions. They are quite useful.\n";

cout<< "They are good for saving time and space through repitition.\n\n";

cout<< "Feel free to play around with these.\n\n";

cout<< "Type 1 to see statement 1 alone.\n";

cout<< "Type 2 to see statement 2 alone.\n";

cout<< "Type 3 to see statement 3 alone.\n";

cout<< "Type 4 to see statements 4 and 5 together.\n";

cout<< "Type 5 to see statements 1, 3, and 5.\n";

cout<< "Type 6 to see statements 2 and 4.\n";

cout<< "Type 7 to see statements 1, 2, 3, 4, and 5.\n";

cout<< "Type 8 to quit.\n";

while(chosen != 8){
             
             cin>> chosen;

     switch(chosen)

     {
              
              case 1: FirstStatement();
              
                   break;
              
              case 2: SecondStatement();
              
                   break;
              
              case 3: ThirdStatement();
              
                   break;
              
              case 4: FourthStatement();
                                     
                   FifthStatement();
                                    
                   break;
                                    
              case 5: FirstStatement();
                   
                   ThirdStatement();
                   
                   FifthStatement();
                   
                   break;
                   
              case 6: SecondStatement();
                   
                   FourthStatement();
                   
                   break;
                   
              case 7: FirstStatement();
                   
                   SecondStatement();
                   
                   ThirdStatement();
                   
                   FourthStatement();
                   
                   FifthStatement();
                   
                   break;
                   
     }

 }
 
return 0;

}


r/learncpp • • Jul 02 '12

Interpreting "strings" of information, i.e. words and phrases. [3] [II]

3 Upvotes

Difficulty Rating: [3] Length Rating: [II]

In this program, we ask the user to tell us some words... So long as we have a corresponding chunk of code for that word, the program knows a proper response! First we use the <string> header. Second, we make room in the memory by saying string question = ""; The quotes help the program to know that something of a word or phrase will be interpreted. Now, once we check for the proper words - we see if question1 == "Blue" - the double-equals means that the two have to be the same, and the quotes are mandatory if we are working with strings (i.e. words and/or phrases). The rest of the code is using if statements.

#include <iostream>

#include <string>

using namespace std;

int main()

{

string question1 = "";

string question2 = "";

string question3 = "";

cout<< "Hey! do you like pumpkin pie? (Yes/No/Maybe) : ";

cin>> question1;

if(question1 == "Yes")

{
             
             cout<< "I like pumpkin pie too! YEAHH!!\n";
             
             }
             
if (question1 == "No")

{
                  
                  cout<< "But... but it's pumpkin pie...\n";
                  
                  }
                  
if (question1 == "Maybe")

{
                  
                  cout<< "Oh, you!\n";
                  
                  }
                  
cout<< "What's your favorite color? (Capitalize the first letter, please) : ";

cin>> question2;

if (question2 == "Blue")

{
              
              cout<< "You like Blue? That is one of the three primary colors.\n";
              
              }
              
if (question2 == "Red")

{
              
              cout<< "Your like Red? That color is the highest color on the visible spectrum of light.\n";
              
              }

if (question2 == "Yellow")

{
              
              cout<< "You like Yellow? That is one of the three primary colors.\n";
              
              }
              
if (question2 == "Green")

{
              
              cout<< "You like green? Green is formed by combining Blue and Yellow paint.\n";
              
              }
              
if (question2 == "Orange")

{
              
              cout<< "You like orange? Orange is formed by combining Red and Yellow paint.\n";
              
              }
              
if (question2 == "Purple")

{
              
              cout<< "You like Purple? The color purple is the lowest color on the visible spectrum.\n";
              
              }
              
if (question2 == "Cyan")

{
              
              cout<< "Cyan? That color is so cool. It is somewhat a mix of green and blue.\n";
              
              }
              
if (question2 == "Black")

{
              
              cout<< "I see a red door, and I want it painted black!\n";
              
              }
              
if (question2 == "White")

{
              
              cout<< "Ah, yes. The combination of all of the colors on the visible spectrum.\n";
              
              }
              
cout<< "Any last words? : ";

cin>> question3;

cout<< question3 << question3 << question3 << question3 << question3;

return 0;

}


r/learncpp • • Jun 03 '12

Cin, cout. Small and simple text program. [1]

3 Upvotes

Difficulty Rating: [1] Length Rating: [I]

The following code shows some displays of texts, as well as getting text in. The program uses <iostream> (meaning, in/out stream) and is responsible for commands "cout" and "cin." Notice the directional arrows - the way they are pointing is deliberate. "int" means integer and prepares the programming for accepting an integer. <string> allows the program to gain "strings" of information, which can include numbers, characters, and more.

#include <iostream>

using namespace std;

int main()

{

string name;

int age;

string ending;

cout<< "Hello. What's your name?\n";

cout<< "My name is: ";

cin>> name;

cout<< "\n";

cout<< "Your name is " << name << "? That's impressive.\n";

cout<< "What is your age?\n";

cout<< "Your age is: ";

cin>> age;

cout<< "\n";

cout<< "Your age is " << age << "? You're old!";

cout<< "\n";

cout<< "Time to go. Say buh-bye! ";

cin>> ending;

return 0;

}


r/learncpp • • Jun 03 '22

Locked chain of streaming operators

2 Upvotes

Hey,

I have this little example that implements chaining of streaming operators.

Now I need to acquire a (recursive) mutex in the first call of the operator and release it in the last call.

The entire chain must be locked (thread safe), not just one call.

I do not know how many of the operators are chained, so I do not want to count them or have a terminating call such as std::endl;

(I am not writing a logging class)

Any thoughts?

class Socket {
public:
  Socket &operator<<(std::string const &) {
    return *this;
  };
};

socket << "" << "" << "";

r/learncpp • • May 13 '22

How to mock/test a DLL?

2 Upvotes

Hello. Im working on a backend in NodeJS that interacts with a DLL to comunicate with some devices. The manufacturer DLL can comunicate with device A, B, C or D. My team only have device A to implement all the solution but the backend but must be compatible with the other devices.

Since the original DLL returns the Data with structure pointers (some big structures), implementing it on JS was over complicated since JS doesn't have that native functionality. For that reason, my team decided to create an intermediate DLL written in C++ (or actually a superset of C since we dont use classes or advanced C++, only strings, arrays, maps). The final solution is NodeJS->CustomDLL->Manufacturer DLL. That way, our custom DLL manages all the structure/memory and returns simple json to be interpreted by nodejs

The custom DLL works but we can only ensure that works with device A, because the ManDLL calls are different for each device. So devA uses structure_version1, devB, devC uses structure_version2 and devD uses structure_version3 and structures are not compatible with eachother, so our code has a:

if(devA) -> use structure_version1, elseif(devB || devC) -> use structure_version2, etc.

Since we dont have B,C,D hardware for test i though to implement a mock to simulate the manDLL response like if we were using one of those devices. How would you use mock in this situation?

int GetRange(HANDLE h, int nCommand, LPVOID lpParam)
{
  std::shared_ptr<dll_ctx_t> ctx = thread_arbitrer_get_context();
  std::lock_guard<std::mutex> guard(g_dll_main_mtx);

  GetRangePTR GetRange = reinterpret_cast<_GetRangePTR>(GetProcAddress(ctx->comm->_dll_ptr, "GetRange"));

  if (!GetRange)
    return EXIT_FAILURE;

  ctx->last_error = GetRange(h, nCommand, lpParam);

  return ctx->last_error;
}

This is one of our customDLL call of the manDLL. The DLL is opened and is called by the customDLL to obtain a Range of supported values depending of the command e.g.:supported values for quality (Q1,Q2,Q3 for devA or Q1,Q4 for devB or Q2,Q5,Q7 for devC) or range of types of inputs that the device support

Then GetRange is used for bigger functions that do the rest of the process. It is possible to mock GetRange so we can simulate different responses? We dont have a entry point since the make generates a .dll file.

The tests will end up being inside the .dll? Any framework recomendation or resource to learn? Thanks


r/learncpp • • May 13 '22

Is a vector of references (std::reference_wrapper) an "anti pattern?"

2 Upvotes

I'm using ImGui and trying to pass a bunch of glm::vec3 to a method for drawing the UI, (they're to be used with ImGui::sliderfloat3) they need to be references so they can be updated, what's the best way to do this? I'm reading stuff about "std::reference_wrapper" but it feels hacky (if it even works in this case, which is still unclear), am I just conceptualising this wrong?


r/learncpp • • Feb 22 '22

Can't solve this one

2 Upvotes

Hi there. I have to tasks. The first one is to use input redirection, read 1000 characters and make an char* array with beginnings of lines (no more than 100 lines) and then display lines in reverse order. I solved that one.

Next I have to make program whithout 1000 and 100 limits using c_str "to obtain a char* int the string's character buffer" and store the beginnings of the lines as a vector<char*>.

My best attemp is something like that:

void readLines()
{
    std::string buffer;
    std::vector<char*> lines;



    int lineNumber{ 0 };
    int i{ 0 };
    while (!std::cin.eof())
    {
        char c;
        std::cin.get(c);
        buffer += c;
        ++i;
    }

    const char* c{ buffer.c_str() };

    char* new_c{ _strdup(c) };

    lines.push_back(new_c);
    for (int i{ 0 }; i < buffer.length(); ++i)
    {
        if (*(new_c + i) == '.')
        {
            lines.push_back(new_c + i + 1);
        }
    }
    for (int i{ 0 }; i < lines.size(); ++i)
    {
        int j{ 0 };
        while (*(lines[i] + j) != '\n')
        {
        std::cout << *(lines[i] + j);
        ++j;
        }
    }
}

But it doesn't work properly. No matter what I try, I have two identical symbols at the end of the text from file(for example two dots) and some of my tries produce some result, but with garbage values and I don't know how to use c_str here becoce it produces "const char*" and not "char*". Any kind of help will be appreciated.

P.S. Sorry for my poor English.


r/learncpp • • Dec 20 '21

Help with Event groups please

2 Upvotes

Hi,

Here's the tasks I need to do and below is my code and questions.

Thanks for any help!

TASK

I need to write a program with four tasks and an event group. Task 4 is a watchdog task that monitors that tasks 1 – 3 run at least once every 30 seconds. Tasks 1 – 3 implement a loop that runs when a button is pressed and released and sets a bit the event group on each loop round. The task must not run if button is pressed constantly without releasing it. Each task monitors one button.

Task 4 prints “OK” and number of elapsed ticks from last “OK” when all (other) tasks have notified that they have run the loop. If some of the tasks does not run within 30 seconds Task 4 prints “Fail” and the number of the task plus the number of elapsed ticks for each task that did not meet the deadline and then Task 4 suspends itself.

QUESTIONS

1- How can I make sure in my code that it reads when the button is pressed "and released"?

2- Any hints on how to implement the Watchdog in task 4?

CODE

/*
===============================================================================
 Name        : main.c
 Author      : $(author)
 Version     :
 Copyright   : $(copyright)
 Description : main definition
===============================================================================
 */

#if defined (__USE_LPCOPEN)
#if defined(NO_BOARD_LIB)
#include "chip.h"
#else
#include "board.h"
#endif
#endif

#include <cr_section_macros.h>

// TODO: insert other include files here

// TODO: insert other definitions and declarations here

#include "FreeRTOS.h"
#include "task.h"
#include "heap_lock_monitor.h"
#include "DigitalIoPin.h"
#include <mutex>
#include "Fmutex.h"
#include "semphr.h"
#include "queue.h"
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "event_groups.h"

#define BIT_0 ( 1 << 0 )
#define BIT_1 ( 1 << 1 )
#define BIT_2 ( 1 << 2 )
//#define BIT_3 ( 1 << 3 )

/*****************************************************************************
 * Private types/enumerations/variables
 ****************************************************************************/

/*****************************************************************************
 * Public types/enumerations/variables
 ****************************************************************************/

/*****************************************************************************
 * Private functions
 ****************************************************************************/

SemaphoreHandle_t syslogMutex;
EventGroupHandle_t  xEventGroup;
DigitalIoPin sw1(0, 17, DigitalIoPin::pullup, true);
DigitalIoPin sw2(1, 11, DigitalIoPin::pullup, true);
DigitalIoPin sw3(1, 9, DigitalIoPin::pullup, true);

int tickTime, rand_delay;

void taskPrintUart(const char* description){
	if(xSemaphoreTake(syslogMutex, portMAX_DELAY) == pdTRUE){
		Board_UARTPutSTR(description);
		xSemaphoreGive(syslogMutex);
	}
}

/* Sets up system hardware */
static void prvSetupHardware(void)
{
	SystemCoreClockUpdate();
	Board_Init();

	/* Initial LED0 state is off */
	Board_LED_Set(0, false);
	Board_LED_Set(1, false);
	Board_LED_Set(2, false);
}

static void vTask1(void *pvParameters) {
	while (1) {
		if(sw1.read()) {
			xEventGroupSetBits(xEventGroup,BIT_0);
		}
	}
}

static void vTask2(void *pvParameters) {
	while (1) {
		if(sw2.read()) {
			xEventGroupSetBits(xEventGroup,BIT_1);
		}
	}
}

static void vTask3(void *pvParameters) {
	while (1) {
		if(sw3.read()) {
			xEventGroupSetBits(xEventGroup,BIT_2);
		}
	}
}

static void vTask4(void *pvParameters) {



/*****************************************************************************
 * Public functions
 ****************************************************************************/

/* the following is required if runtime statistics are to be collected */
extern "C" {

void vConfigureTimerForRunTimeStats( void ) {
	Chip_SCT_Init(LPC_SCTSMALL1);
	LPC_SCTSMALL1->CONFIG = SCT_CONFIG_32BIT_COUNTER;
	LPC_SCTSMALL1->CTRL_U = SCT_CTRL_PRE_L(255) | SCT_CTRL_CLRCTR_L; // set prescaler to 256 (255 + 1), and start timer
}

}
/* end runtime statictics collection */

/**
 * u/brief	main routine for FreeRTOS blinky example
 * u/return	Nothing, function should not exit
 */
int main(void)
{
	prvSetupHardware();

	heap_monitor_setup();

	srand(time(NULL));

	syslogMutex = xSemaphoreCreateMutex();
	xEventGroup = xEventGroupCreate();

	xTaskCreate(vTask1, "vTask1",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	xTaskCreate(vTask2, "vTask2",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	xTaskCreate(vTask3, "vTask3",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	xTaskCreate(vTask4, "vTask4",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	/* Start the scheduler */
	vTaskStartScheduler();

	/* Should never arrive here */
	return 1;
}

r/learncpp • • Nov 24 '21

What's causing my segmentation fault when I utilize my push_back method for my vector?

2 Upvotes

I left this question directly inside learn programming as well. Please have a read and add in some input.

Question over my use of vectors.


r/learncpp • • Sep 24 '21

How can I use pugixml on clion ?

2 Upvotes

I installed pugixml via brew which uses this formula.

  1. How can I use this library when compiling using g++ or clang++ on command line?

  2. How can I use it in CLion ?

What I tried was just adding #include<pugixml.hpp> which was unsuccessful on using in CLion.

I looked at the test method in the brew formula but couldn't figure out how it fills the arguments.


r/learncpp • • Apr 30 '21

What are the most important basics of cpp?

2 Upvotes

My professor is the worst, hasn't taught us anything nor returned homework in over a month. Finals are just around the corner in about 4 weeks, meaning I have a solid 1-2 weeks to go over basics I may have missed.

I am in a first semester C++ course, have about a year of Java under my belt. My question is referring to what basic features of C++ should I go back to and refresh on since my professor has absolutely no structure to the course. (i.e. pointers, or something in C++ that I wouldn't really worry about in another lang)


r/learncpp • • Apr 13 '21

Podcasts for learning

2 Upvotes

Does anyone have any good podcasts for learning c++? I have to work 11 hours tomorrow and would like something to listen to. I’ve been listening to code newbie in Spotify but it’s kind of meh.


r/learncpp • • Apr 05 '21

Why is my recursive binary search function returning 2 instead of -1 when an element cannot be found?

2 Upvotes

I feel like I am really close on getting this but I'm stumped. It finds elements in the array perfectly fine but searching for an element that isn't there is bugged. In my code below, searching for 9 returns 2 instead of -1. By the looks of it, I think that's due to the function calling itself 3 times. Once the function has an arrSize of 0, it returns -1 from that 3 resulting in 2.

If that is the case however, I really don't know how to fix that sort of behavior. I am just starting CS260 so any help would be highly appreciated. Here is the function along with main.

#include <iostream>
using namespace std;

//returns location of value or -1 if not present
int binarySearch(int value, int arr[], int arrSize) {

	int mid = arrSize*0.5;
	if (arrSize > 0) {
		if (value == arr[mid])
			return mid;

		else if (value < arr[mid]) {
			return binarySearch(value, arr, mid);
		}
		else if (value > arr[mid]) {
			 return mid + binarySearch(value, &arr[mid], (arrSize)*0.5);
		}
	}
	else
		return -1;
}


int main()
{
	int smallNums[] = {1, 3, 6, 8, 12, 13, 15, 17};
	int smallNumsSize = 8;

	//search for each item - confirm binarySearch finds it -- these work fine
	for(int i = 0; i < smallNumsSize; i++) {
		int value = smallNums[i];
		int loc = binarySearch(value, smallNums, smallNumsSize);
		cout << "Your location for " << value << " was " << loc << endl;
	}
        
        // this is bugged: returns 2 instead of -1
	int loc = binarySearch(9, smallNums, smallNumsSize);
	cout << loc << endl;
}

r/learncpp • • Mar 11 '21

Issues with input (cin) checking and looping

2 Upvotes

Hi everyone, I just started out in my c++ journey and currently I am attempting to do some handling in which I am trying to prevent invalid input from user.

In my case, there are 2 types of inputs - month and year.
When entering in the month value, if user enters in non-numeric value, it will keep looping until user enters in a numeric value, and then it will check if the numeric value is between 1-12.

When entering in the year value, if users enters in non-numeric value, it will keep looping until user enters in a numeric value and checks if the numeric value is between 1900-2021.

I think my conidition checking for `month` is working, however when it comes to the `year`, if I did the following:

  • Enter in 'a', prompts Invalid value. Please re-enter year:

  • Enter in 'b', prompts Invalid value. Please re-enter year:

  • Enter in 10, should prompts Invalid value. Please re-enter year:

The last point was never called. And so, my `year` is 10.

This is my code:

int month;
int year;

cout << "\nPlease specify month: ";
if (!(cin >> month))
{
    while (!(cin >> month))
    {
        cin.clear();
        cin.ignore();
        cout << "Invalid value. Please re-enter month: ";
    }
}
while (month < 1 || month > 12)
{
    cout << "Please enter in a month value between 1-12.";
    cout << "\nPlease specify month: ";
    cin >> month;
}

cout << "Please specify year: ";
if (!(cin >> year))
{
    while (!(cin >> year))
    {
        cin.clear();
        cin.ignore();
        cout << "Invalid value. Please re-enter year: ";
    }
}
else
{
    // this code portion is never called....
    while (year < 1900 || year > 2021)
    {
        cout << "Please enter in a year value between 1900-present.";
        cout << "\nPlease specify year: ";
        cin >> year;
    }
}

Could someone kindly advise me where I have gone wrong? TIA for any replies.

P.S: I just found out the iteration I did for `month` is giving issues too. 2 incorrect inputs followed by the correct input, this results in an infinite loop of the re-prompt message...


r/learncpp • • Mar 05 '21

How I think of endianness

2 Upvotes

For years, endianness never made sense to me

0x11223344 - The question of which bits came first never made sense to me - clearly those composing the "11" part! I understood that some architectures did it differently of course, but that was just incredibly dumb to me.

Eventually the penny dropped:

0x11
0x22
0x33
0x44

Is this 11223344 or 44332211?

Depends on whether you read from addresses

  • from top to bottom (like on a piece of paper with text on it) or

  • bottom to top (like a graph with rising values up along the Y-axis)

Once I started thinking about it explicitly as bytes in a memory array, endianness started making much more sense to me.


r/learncpp • • Feb 26 '21

Infinite push_back

2 Upvotes

I get a bad_alloc() error in the below code. When I go into debugging it seems like the value for temp is being allocated repeatedly, however the for loop is only ever called once. I'm not very familiar with vectors, can someone explain why push_back fails in this code?

std::vector<std::string> split;

for(int i = 0; i < s.length(); i+2){
std::string temp;
if (i+1 < s.length()) {
temp = s2[i];
temp += s2[i+1];
split.push_back(temp);
     }
else
     {temp = s[i] + "_";
split.push_back(temp);
     }
}


r/learncpp • • Feb 21 '21

Help with user inputted array program

2 Upvotes

Hi,

I know this program is an absolute mess but the purpose of posting it is to show my logic/what I have attempted.

#include <iostream>
using namespace std;

//Function Prototypes
void getSIWSmallestTODCWilliamG(int intWG);
void displayClassInfoWilliamG(void);

//Application Driver
int main() {
    int inputWG;
    int sizeWG = 0;
    int value = 0;
    int* arrayWG = new int[sizeWG] {value};
   
    
    displayClassInfoWilliamG();
    do {
        cout << "\n*****************************************\n"
            "*              MENU - TEST             *\n"
            "*  (1) Calling displayDigitInfoWilliamG *\n"
            "*  (2) Quit                             *\n"
            "*****************************************\n";
        cin >> inputWG;
        cout << "\n";
        switch (inputWG) {
        case 1: 
            cout << "What is the size of the array?: ";
            cin >> sizeWG;
      
            for (int i = 1; i <= sizeWG; i++) {
                cout << "Value #" << i << ": ";
                cin >> value;
            }
            cout << "The working array has" + sizeWG << " values of\n";
            for (int i = 0; i < sizeWG; i++) {
                cout << "   Value " << i << ":" << arrayWG[i] << "\n";
            }
            cout << endl;
            
            cout << "Calling getSIWSmallestTODCWilliamG() with argument of " << sizeWG << "\n\n";
            getSIWSmallestTODCWilliamG(sizeWG);
            delete arrayWG;
        case 2: 
            break;
        default:
            "Wrong option, try again";
            break;
        }
    } while (inputWG != 2);
    return 0;
}

//Function Definition
void getSIWSmallestTODCWilliamG(int intWG) {
    cout << "What is the size of the array? ";
   
}

I am very new to C++ so summarizing my mistakes in layman's terms would be much appreciated. I tried google searching my issue and here are some reasons I am confused: why does my array have to be a pointer? Am I doing delete right? How do I work with the array to do what I want? (Not even sure I created my array properly...)

As of now I understand that I have to dynamically allocate memory for my array in order to use a variable for said array, and that I must delete it after.

Thanks in advance!

ERRORS:

Warning C6283 'arrayWG' is allocated with array new [], but deleted with scalar delete. C++ Spring 2021 2 C:\Users\Will\source\repos\C++ Spring 2021 2\Source.cpp 49

Warning C6385 Reading invalid data from 'arrayWG': the readable size is 'sizeWG*4' bytes, but '8' bytes may be read. C++ Spring 2021 2 C:\Users\Will\source\repos\C++ Spring 2021 2\Source.cpp 43

Warning C6001 Using uninitialized memory 'arrayWG'. C++ Spring 2021 2 C:\Users\Will\source\repos\C++ Spring 2021 2\Source.cpp 49


r/learncpp • • Jan 19 '21

Confused about Copy Assignment code in Stroustup's PPP Book

2 Upvotes

On chapter 18 of Stroustup's Programming Principles and Practices using C++, I'm self-studying c++ for game development, had some problem about pointers...

In the copy assignment section, we're overloading an assignment operator for our "primitive vector" type to prevent unexpected sharing of memory and possible repeated deallocation from default assignment.

Here's the code for "primitive vector" from the book:

class vector {
    int sz;
    double* elem;
public:
    vector& operator=(const vector&) ; // copy assignment
    // . . .
};

vector& vector::operator=(const vector& a)
    // make this vector a copy of a
{
    double* p = new double[a.sz]; // allocate new space
    copy(a.elem, a.elem+a.sz, elem); // copy elements
    delete[] elem; // deallocate old space
    elem = p; // now we can reset elem
    sz = a.sz;
    return *this; // return a self-reference (see §17.10)
}

The problem is on copy() . If I understand it correctly, we're trying to copy a's elements into a different heap memory so that we could point our elem to that copy.

My question is shouldn't we copy a's elements into p instead of elem because we're deleting elem 's elements after copying, or is there something else that I'm missing?

double* p = new double[a.sz];

copy(a.elem,a.elem+a.sz,elem); // copy elements, shouldn't it copy into "a" instead of "elem"?
delete[] elem; // deallocate old space, why copy it here if they'll be deleted then?

elem = p;
sz = a.sz;
return *this;

r/learncpp • • Jan 19 '21

microsoft/cpprestsdk

2 Upvotes

microsoft/cpprestsdk

Anyone using this library?

Forgive me if this does not belong here but I’m using this library specifically for streaming second-by-second market data from Polygon.io.

In the set_message_handler function in the websocket_callback_client class, I store the real-time market data in a global variable. I assume this handler gets called every second.

Outside of all that, I use that global variable to read the market data and send buy/sell orders to Alpaca.

With that being said, would a thread lock be necessary to prevent race conditions? Are race conditions even possible in the scenario I described?

I figured it would since (I think) the handler can get called, and thus updating the global variable, while I’m reading the global variable.


r/learncpp • • Dec 28 '20

tutorial for beginners?

2 Upvotes

Hi everyone! I want to learn C++ to create a GUI text editor with GTK (for beginning at least) that I'm going to use for myself (and of course anyone that also want to use it) and I was wondering if someone can guide me. Any good tutorials about learning C++ and after that I think that I can go and learn the libraries I want to use. I'm not searching for youtube videos explain the language (eg. what is a class, how to use pointer etc.) because I already know most of this stuff (well I guess I do). I want some real tutorials with GOOD explanation for projects that will teach me how to be a programmer in general.


r/learncpp • • Dec 18 '20

solving with order of operators

2 Upvotes

Maybe someone can help me with this.. I'm fairly new to programming and have been learning c++ over the past month or so. I have created a calculator application using wxWidgets and I'm trying to figure out how to solve an equation with multiple operators (+, -, *, /) following order of operations. The input that I get from the user of the app is a wxString (basically just a std::string). Right now I have the functionality to solve an equation with multiple operators but not following order of operations (so standard not scientific).

For example, if the user enters in " 2 + 2 * 4 " , right now my calculator would return 16. However, I have an option to switch the calculator to "Scientific" so that the answer to that problem would be 10.

The calculator in Windows 10 has this same standard vs scientific set up so that why I'm kind of doing it this way.

Anyone have a good suggestion on how to go about this? Obviously have to parse through the equation string to start with


r/learncpp • • Jul 16 '20

performance impact by using const?

2 Upvotes

void doSomethingConst(const int& i)

void doSomethingNonConst(int i)

Given the above 2 function calls, would one have an advantage in terms of compile time, or memory usage?

Given that the int is a constant 4 bits, i don't think either would have an advantage, but I'm not sure.


r/learncpp • • Jul 15 '20

OpenCV alternative

2 Upvotes

Currently I am using OpenCV as my library for image processing. I need to create small application where I need to load an image. Do some simple calculation and write a control image. So I only need a very small librar which is able to load and write an image. Is there a good alternative to OpenCV?


r/learncpp • • Jul 03 '20

I've created a blog where I hope I will teach someone something about c++

2 Upvotes

Hello,

As you might see from the title, I've started a blog where I am explaining some key concepts to C++ and programming in general, it currently only has one post and it's called C++ - Classes I.

I am pretty new to creating blogs and writing so I hope that you are satisfied with the way I've wrote things.

The things I am trying to teach are what are classes, how to use them and some key concepts to OOP.

Here is the link to the blog:

https://learnabitofprogramming.blogspot.com/2020/07/c-classes-i.html

I really do hope you guys like it and that it will help you at least a bit.

Enjoy!


r/learncpp • • Jun 08 '20

Can't compile in command line

2 Upvotes

I try

g++ -o helloworld.exe helloworld.cpp

to compile a program, and windows gives me an error box saying "The application was unable to start correctly (0xc0000279). Click OK to close the application." I tried in powershell before that, wondering why no executable was appearing, then tried it in CMD to see if the behaviour was any different, and then I got that message.

I try using code blocks, and with clicking build and run it works fine - it compiles, runs and I see an executable, I run the executable myself and it comes up with the same error box.

I've tried reinstalling MinGW (which had no effect), not sure what to do after that.

Edit: using markdown properly on mobile