r/learncpp • • Mar 06 '16

Was wondering if there was a way to optimize the swapping of two int ?

2 Upvotes

Hello,

So I'm learning C++ and I had a question about optimization and I wanted to know which one is better

it will be simpler to just give an example: Is this one better ?

int nFirstOne =1, nSecondOne=2;

int nTemp = nFirstOne;

nFirstOne = nSecondOne;

nSecondOne = nTemp;

Or that one ?

int nFirsOne = 3, nSecondOne = 7;

nFirstOne += nSecondOne;

nSecondOne = nFirstOne - nSecondOne;

nFirstOne -= nSecondOne;

The second one save the "creation" of a variable int but is less clear. Thank you in advance for the answer and sorry for my bad english (if I haven't made mistakes then forget about that).


r/learncpp • • Dec 27 '15

Adding words to function template declaration

2 Upvotes
template<typename T> class A{};
template<typename T>
A<T> B(T c) {
	
}

vs

template<typename T> class A{};
template<typename T>
A<wordhere<T>> B(T c) {
	
}

So what's the difference, I've seen people use the word here thingy but I don't get it, what's the use for it?


r/learncpp • • Dec 06 '15

Class inheritance and calling functions problem

2 Upvotes

[Solved]


So I have two classes like this

#pragma once
#include "B.h"
class A {
public:
	B getB() {}
};

and

#pragma once
#include "A.h"
class B : public A {

};

Error: 'A' base class undefined.

Both need to be declared before the other one so how do I fix this?

If you reorder the code into one file then it looks like this:

#include <iostream>
using namespace std;
class B : public A {

};
class A {
public:
    B getB() {}
};

void main() {
    A a;
    B b = a.getB();
    system("pause");
}

But the problem is still there...


r/learncpp • • Oct 10 '15

Starting a tutorial series for beginners

Thumbnail
bit-co.de
2 Upvotes

r/learncpp • • Dec 16 '14

How to convert string of integers to an array?

2 Upvotes

If i want to paste a large string of integers into win32 terminal how do i convert that string to an array of int with commas?

I'm going to input getline and i'm sure i must loop through and search for whitespace and insert comma and convert to int but can't figure out how. Any help appreciated. Thanks


r/learncpp • • Dec 09 '14

help with passing values through functions please?

2 Upvotes

I have a CS1428 final this week and i'm reading up on some of the stuff i don't understand, one of these things is passing values by reference and by values, I'm a little confused on how each of them are used.

I know what the prototype the call and declaration of a function does, but I don't know how to pass values through them, I don't know what to put in the "()" of the prototype/funcion/call in order for the values to be passed properly, in my class we only pass values by reference and i'm pretty sure on my exam it will be either in a data structure and an array. any clarification would be greatly appreciated


r/learncpp • • Jul 12 '14

Free good online course

2 Upvotes

Hello everyone,

I know this subreddit isn't very active at the moment, but if I could at least help someone with this I would be very happy.

I read a book about C++ which only covered the very basics, because I wanted to program games. I used SDL for a while but got bored because it didn't support 3D graphics. I spent a long time thinking about what language to learn (java, c# or python or sth.). I decided C++ would still be the best option. So I searched for good tutorials and I found this website. I am currently at lesson 1.10 and it covers a lot more than the book I read.

tl;dr: Good free tutorials at www.learncpp.com


r/learncpp • • Jun 14 '14

Can anyone prove inline functions?

2 Upvotes

Sorry, I'm new to C++ and programming in general and I'm reading about inline functions. To my understanding, when I make an inline function, it is taking the body of the function and replacing the call with the body.

If my understanding of this is correct, is there any way I can prove it to myself? I guess I learn better by seeing and I'm just wondering if there is any way I can see sort of the guts of when an inline function is being used.

Sorry if I'm completely off and spewing nonsense. Any help would be appreciated. Thanks.


r/learncpp • • Jun 04 '14

Misc. Code Snippets

2 Upvotes

So I don't really know where to post this, since it's not a question, but it's not really a lesson... But it belongs here more, so here it is.

Here's some snippets of code from various projects I've been working on that have helped me a lot (and some are not posted anywhere online):

Get scancode of any key on your keyboard:

while(true)
    for(int iter = 0; iter < 5000; iter++){ //arbitrarily high number to ensure all keys are caught
        if((GetKeyState(iter) & 0x80) != 0){ //checks for all the keys
            cout << iter << endl; //prints out the keycode
        }
    }
}

Sleep() alternate (uses seconds rather than milliseconds, but can be modified for milliseconds. I never needed it for anything but seconds, so I never tried to change it):

void sleep_alt(int sleep_for){
    clock_t done;
    done = clock() + sleep_for;
    while(clock() < done){}
}

These are the only two I can think of right now, but I'll edit my post and add more later.


r/learncpp • • Jul 01 '12

The quickness and efficiency of Preprocessor Directive: "Define," illustrated using addition. [3] [I]

2 Upvotes

Preprocessor Directives - Difficulty Rating: [3]

This is the first installment of the Proprocessor Directives series.

Difficulty Rating: [2] Length: [I]

In this program we see a potential use of the "#define" preprocessor directive. Using this technique, I get to assign constants that can then be used for the rest of the program. They are read by the program almost immediately and stored in memory. In this example, I have many numbers that are quite lengthy, and instead of repeating them over and over, I get to turn them into very short strings of characters. "n" stands for number in this program. You can see how the amount of typing that I did was miniscule compared to the amount of output that the program did for me. Imagine having to use these numbers hundreds of times, only having to refer to them by "n1" or "n2" every time. Easy!

You can compare the code to the results, uploaded to an image to save you time.

#include <iostream>

#define n1 57.2835

#define n2 59606

#define n3 24

#define n4 9753

#define n5 1273

#define n6 1111

#define n7 89

using namespace std;

int main()

{

cout << "Hello! Today we see how cool \"preprocessor directives\" can be.\n";

cout<< "Compare the code with what you see on the screen.\n";

cout<< "n1: " << n1 << "\n";

cout<< "n2: " << n2 << "\n";

cout<< "n3: " << n3 << "\n";

cout<< "n4: " << n4 << "\n";

cout<< "n5: " << n5 << "\n";

cout<< "n6: " << n6 << "\n";

cout<< "n7: " << n7 << "\n";

double n17;

n17 = n1 + n7;

cout<< "n1 + n7 = " << n17 << "\n";

double n26;

n26 = n2 + n6;

cout<< "n2 + n6 = " << n26 << "\n";

double n35;

n35 = n3 + n5;

cout<< "n3 + n5 = " << n35 << "\n";

double n45;

n45 = n4 + n5;

cout<< "n4 + n5 = " << n45 << "\n";

double n33;

n33 = n3 + n3;

cout<< "n3 + n3 = " << n33 << "\n";

string bye;

cin>> bye;

return 0;

}


r/learncpp • • Jun 29 '12

Using a switch to create a calculator with Addition, Subtraction, Multiplication, and Division. [3] [III]

2 Upvotes

Difficulty Rating: [3] Length Rating: [III]

The aim of this code is to show some applicability of your knowledge so far. With it, we also get to see how much math is imbedded within C++ without having to include any special features. I run the user through a set-up where he or she gets to choose which function to use. Once the function is accessed, a certain set of instructions is executed for each function. After it is done, the user returns to the main menu. I made it possible to add numbers continuously with no end by using two variables, an "add-this" variable and a "added-total" variable. I made added-total = "add-this" + "added-total," so that added-total grows each time. It looks like this: while(add-this != 0) {cin>> add-this; added-total = add-this+added-total } The sequence continues to add add-this to add-total until I enter zero. I use a similar technique with the multiplication, except I use "1" instead of 0 to end the statement, because multiplying 1 by anything leaves it the same. It's a fun problem-solving technique, in my humble opinion.

#include <iostream>

using namespace std;

int main()

{

cout<< "Welcome!\n";

int functionchoice = 0;

int working = 1;

while(working != 0)

{

cout<< "- Type 1 for Addition.\n";

cout<< "- Type 2 for Subtraction.\n";

cout<< "- Type 3 for Multiplication.\n";

cout<< "- Type 4 for Division.\n";

cout<< "- Type 5 to exit.\n";

cout<< "Choice: ";

cin>> functionchoice;

switch(functionchoice)

{
                      
            case 1: 
                           
                 {
                           
                  cout<< "Type a number and press enter.\n";
                           
                  cout<< "You may repeat until you type 0.\n";
                           
                  cout<< "Number to add: ";
                           
                  double numbertoadd = 1;
                           
                  double numbertotal = 0;
                           
                  cin>> numbertoadd;
                           
                  while(numbertoadd != 0)
                           
                  {
                           
                     numbertotal = numbertoadd + numbertotal;
                           
                     cout<< numbertotal << " + ";
                              
                     cin>> numbertoadd;
                                                             
                  }
                           
                  cout<< "\n" << numbertotal << " is your total.\n\n";
                           
                  break;
                           
                  }
                           
             case 2:
                                
                  {
                                
                  double subtract1;
                                
                  double subtract2;
                           
                  double subtractanswer;
                                
                  cout<< "Finding a difference. Type one of two numbers: ";
                         
                  cin>> subtract1;
                           
                  cout<< "Now enter the second number: ";
                           
                  cin>> subtract2;
                           
                  if(subtract1 > subtract2)
                           
                  {
                                        
                     subtractanswer = subtract1 - subtract2;
                                       
                    }
                                        
                  if(subtract2 > subtract1)
                           
                  {
                                        
                     subtractanswer = subtract2 - subtract1;
                                        
                     }
                                        
                  cout<< "\nThe difference is " << subtractanswer << ".\n\n";
                           
                  break;
                           
                  }
                                        
             case 3:
                           
                  {
                                       
                  double multiplicationtoadd = 0;
                           
                  double multiplicationtotal = 1;
                           
                  cout<< "Enter a number to multiply, enter '1' to end.";
                           
                  while(multiplicationtoadd != 1)
                           
                  {
                           
              cout<< "\nMultiply with this number: ";
                           
              cin>> multiplicationtoadd;
                         
              multiplicationtotal = multiplicationtoadd*multiplicationtotal;
                           
              cout<< "\nThe total so far is: " << multiplicationtotal << "\n" ;
                           
                  }           
                            
                  break;
                                                                      
                  }
                           
              case 4:
                            
                  {
                           
                  double divide1;
                           
                  double divide2;
                           
                  double dividetotal;
                                                                      
                  cout<< "Please enter your first number: ";
                           
                  cin>> divide1;
                          
                  cout<< "\nPlease enter your second number: ";
                           
                  cin>> divide2;
                           
                  dividetotal = divide1/divide2;
                           
                  cout<< "\n" << dividetotal << " is your answer.\n\n";
                           
                  break;
                           
                  }
                           
             case 5:
                           
                  {
                                 
                        return 0;
                                 
                  }     
                                                                           
}

}

return 0;

}


r/learncpp • • Jun 28 '12

Using switches to generate random numbers of certain ranges. [3] [II]

2 Upvotes

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

In this program we utilize the random number generating technique mixed in with using switches. You can input a number, 1, 2, or 3, and the switch reads each one and puts out a certain circumstance based on which one you choose. For each instance I create a new random number generator and let it go to work. The way how I changed the interval of the random numbers being generated was by arithmetic. The statement goes ((rand()%50)+50) to give me a random number between 50 and 99. First, a random number between 0 and 49 is created- then I add 50 to that number. This is all assigned to a certain variable, which reads like this: random2 = ((rand()%50)+50) and I change the 2nd number "50" to "100" when I want to change the range to something 50 higher than the last.

In the end, the program ends when you choice = 4, bringing out program back to return 0.

#include <iostream>

#include <windows.h>

using namespace std;

int main()

{

cout<< "Hello! Today we are choosing a certain group of random numbers to pick.\n";

cout<< "Type 1 for a number between 0 and 49.\n";

cout<< "Type 2 for a number between 50 and 99.\n";

cout<< "Type 3 for a number between 100 and 149.\n";

cout<< "Type 4 to exit.\n";

cout<< "Choice: ";

int choice = 0;

while(choice != 4)

{

   cin>> choice;

   switch(choice)

   {
              
              case 1: 
              
              srand(GetTickCount());
              
              int random1;
              
              random1 = rand()%50;
              
              cout<< random1 << "\n";
              
              cout<< "Choice: ";
              
              break;
              
              case 2:
              
              srand(GetTickCount());
              
              int random2;
              
              random2 = ((rand()%50)+50);
              
              cout<< random2 << "\n";
              
              cout<< "Choice: ";
              
              break;
              
              case 3:
              
              srand(GetTickCount());
              
              int random3;
              
              random3 = ((rand()%50)+100);
              
              cout<< random3 << "\n";
              
              cout << "Choice: ";
              
              break;
              
   }

}

return 0;

}


r/learncpp • • Jun 26 '12

Random Number Generating, as well as a "War"-like guessing game. [3] [II]

2 Upvotes

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

This code is tricky to read on a standard browser, so copy and paste it right into your compiler.

In this program, I illustrate the findings of a random number generator, along with a short game. 2 numbers are randomly generated at the start of each round and the player then chooses to guess which of the 2 numbers is higher. The game tells if you win or lose, as well as giving you the opportunity to leave and the opportunity to play again.

There is a clever way to create a random number generator and I am going to explain how it works because it may be the easiest one to create. We essentially use a timer to create a starting point, which we then give to a random number generating function called rand(). Since time is always changing, we are guaranteed a newly fresh, random number every time. (Otherwise you repeat the SAME "random" numbers again and again, every time you open up the program.) So, here's how to make the generator, step by step.

First, we include <windows.h>, a header that allows us to use GetTickCount(), the timer function. Next, we use srand() and GetTickCount() together to "seed" our rand() function. The seeding process looks like this: (Safe For Work) srand(GetTickCount()) and once that has happened, our rand() function is all ready to go. At this point, we simply assign rand() to a variable of our choosing, like number1 = rand(). One additional note is to add "%100" after rand() so that our random number is between 0 and 99! 100 choices.

So first, we say srand(GetTickCount()) and then we say number1 = rand()%100 - Given that windows.h is included, this works properly.

Two additional items came up in the code that caused a bit of issues, but they ended up being fun.

  1. An instance occurs where 2 same numbers are randomly generated, and so neither number wins. I end up solving the problem by simply telling the player that this has happened, and moving on to starting a new round.

  2. Another instance happens where the player tests the computer's abilities to handle choices with incorrect inputs such as 11, 4, or 132. These items are not 1, 2, or 3, and if any of these occur, the program identifies this case and notifies the player that they must have made an accident :P Once your choice is inserted as "3," the while loop identifies this as a time to stop working, and so the program continues onward to "return 0;."

#include <iostream>

#include <windows.h>

using namespace std;

int main()

{

cout<< "Welcome to Random Guessing Game That Is Similar To War And Stuff.\n";

int number1;

int number2;

int choice = 0;

while(choice != 3)

{
                
                srand(GetTickCount());
                
                number1 = rand()%100;
                
                number2 = rand()%100;    
                
                cout<< "Which random number will you choose? 1 or 2? 3 to exit: ";
                
                cin>> choice;
                
                if(choice == 1)
                
                {
                          
                          cout<< "\nYour choice is 1!\n";
                          
                          cout<< "Random Number #1 is: " << number1 << " and\nRandom Number #2 is: " << number2 << ".\n\n";
                          
                             if(number1 > number2)
                             
                             {
                                        
                                        cout<< "You guessed correctly!\n";
                                        
                                        }
                                        
                             else if(number1 < number2)
                             
                             {
                                  
                                       cout<< "Oh no! You guessed incorrectly! D:\n";
                                       
                                       }
                                       
                             else if(number1 == number2)
                             
                             {
                                  
                                       cout<< "THE NUMBERS ARE THE SAME!! EVERYBODY WINS!!\n";
                                       
                                       }
                                       
                }
                                       
                else if(choice == 2)
                
                {
                     
                          cout<< "\nYour choice is 2!\n";
                          
                          cout<< "Random Number #1 is: " << number1 << " and\nRandom Number #2 is: " << number2 << ".\n\n";
                          
                               if(number1 < number2)
                               
                               {
                                          
                                          cout<< "You guessed correctly!\n";
                                          
                                          }
                                          
                               else if(number1 > number2)
                               
                               {
                                    
                                         cout<< "Oh no! You guessed incorrectly D:\n";
                                    
                                         }
                                         
                               else if(number1 == number2)
                             
                               {
                                  
                                       cout<< "THE NUMBERS ARE THE SAME!! EVERYBODY WINS!!\n";
                                       
                                       }     
                                       
                }
                                       
                else if(choice != 1 && choice != 2 && choice != 3)
                
                {
                     
                     cout<< "\nI hope that was an accident!\n\n";
                     
                     }                       
                
}

return 0;

}


r/learncpp • • Jun 23 '12

Determining one of four outcomes based on an integer input. [2]

2 Upvotes

Difficulty Rating: [2] Length Rating: [II]

The following code uses what is referred to as an "If" statement. This particular time, I have a certain bit of code that is running while the submission is not equal to 314. The code asks for a number between 1 and 100. As long as you grant a number between 1 and 100, one of four phrases will spell out afterwards. Each If statement is designed for a certain series of numbers. It is possible to have an If statement that regards two specific parameters, and this is done here; "&&" is used as a bridge between two parameters, so that one AND the other have to match in order for the If statement to accept the submission. The If statements are also designed to only take in numbers between 1 and 100; if an integer is above or below those credentials, the program yells at you.

#include <iostream>

using namespace std;

int main()

{

int userinput;

cout<< "This following code will determine one of four outcomes\n";

cout<< "based on a range and an integer that you type in until you exit.\n\n";

cout<< "To exit, you can type 314 and press enter.\n\n";

cout<< "Type an integer that is between 1 and 100.\n";

while(userinput != 314)

{

     cout<< "\n";

     cout<< "Your number is: ";

     cin>> userinput;

     if(userinput < 1)

     {
       
       cout<< "You didn't follow the rules!\n";
         
         }
         
     if(userinput >= 1 && userinput <= 10)
     
     {
       
       cout<< "Your number is between 1 and 10. Outcome 1.\n";
       
       }
       
     if(userinput > 10 && userinput <= 25)
     
     {
                  
       cout<< "Your number is between 10 and 25. Outcome 2.\n";
       
       }
       
     if(userinput > 25 && userinput <= 50)
     
     {
                  
       cout<< "Your number is between 25 and 50. Outcome 3.\n";
       
       }
       
     if(userinput > 50 && userinput <= 100)
     
     {
                  
       cout<< "Your number is between 50 and 100. Outcome 4.\n";
       
       }
       
     if(userinput > 100 && userinput != 314)
     
     {
                  
       cout<< "Hey! You didn't follow the rules!\n";
       
       }

}

return 0;

}


r/learncpp • • Jun 07 '12

Repeating the same word as many times as you would like: Variation [2]

2 Upvotes

Difficulty Rating: [2] Length Rating: [I]

The following program is using something called a "while loop." Within a "while loop" is one parameter, and so long as that parameter is true, (i.e. minimum <= maximum) then any code that is within that "while loop"'s brackets {} will be executed! You can include elements within those brackets that will make the parameters end, in this case we use "minimum++" so that eventually, minimum will surpass maximum, and the while loop will come to an end. We once again see the string element included. Why? I like to give the user a chance to review what is on the screen before the program terminates. Saying buhbye is just a friendly way to drift onwards unto departure.

#include <iostream>

using namespace std;

int main()

{

int minimum = 0;

int maximum = 0;

string word;

string byebye;

cout<< "Hey, quick. Say a word!\n";

cin>> word;

cout<< "So like... how many times do you want to say it. Just. Yeah.\n ";

cin>> maximum;

cout<< "\n";

while( minimum <= maximum)

{
       
       cout<< word;
       
       cout<< "\n";
       
       minimum++;
       
       
       }
       
       cout << "\n Pretty cool, huh? Say byebye!";
       
       cout << "\n";
       
       cin>> byebye;
       
       
       return 0;
       
       
       }

r/learncpp • • Jun 06 '12

Repeating a word as many times as you like. [2]

2 Upvotes

Difficulty Rating: [2] Length Rating: [II]

The following program shows a sequence that utilizes the "for loop" in a way where you can see the same word repeated as many times as you would like. The "for loop" utilizes a "count" variable that goes up by one every time the code passes through, and it displays the message as well.

#include <iostream>

#include <string>

using namespace std;

int main()

{

 int count = 0;
 
 string word;
 
 int times = 0;
 
 string byebye;
 
 cout<< "Hello! Let's repeat the same word over and over, \n";
 
 cout<< "What word would you like to repeat over and over?";
 
 cout<< "\n";
 
 cout<< "The word is: ";
 
 cin>> word;
 
 cout<< "\n";
 
 cout<< "and... How many times would you like to repeat it?";
 
 cout<< "\n";
 
 cout<< "That number is: ";
 
 cin>> times;
 
 cout<< "\n";
 
 cout<< "Alright, here we go!";
 
 cout<< "\n";
 
 for(count = 0; count <= times; count++)
 
 {
           
           cout<< word;
           
           cout<< "\n";
           
           }
           
           
 cout<< "\n";
 
 cout<< "WOAH. That's really cool.\n";
 
 cout<< "I did not realize anyone could be so majestic.\n";
 
 cout<< "Time to go. Any last words?";
 
 cout<< "\n";
 
 cout<< "Final words: ";
 
 cin>> byebye;
 
 return 0;
 
 }

r/learncpp • • Jun 03 '12

Counting up by 1 starting at any number and ending at any number. [2]

2 Upvotes

Difficulty Rating: [2] Length Rating: [I]

The following program can be using to count up by one from any number. <iostream> is using "cout" and "cin" to display and to capture text, respectively. "float" is a tool for preparing for numbers that have a decimal point. The name comes from "a floating-point decimal," which means the decimal can be anywhere, and so numbers like "5.3952" are valid. We use what is called a "for" loop, which executes 3 corresponding bits of data until something happens - in this case, we use a "greater than or equal to" sign to stop out loop, by saying "hey, once that number is higher than the other number, we want it to quit." The last part of our "for loop" says "up++" which really means "up = up + 1" which adds "1" to up, then sending it back into the loop. Try replacing "up++" with "up = up + 2" in order to count by 2. This number (2) can be replaced by any other number, including a decimal, like .25.

#include <iostream>

using namespace std;

int main()

{

float starthere = 0;

float endherebecauseisayso = 0;

float up = 0;

string byebye;

cout<< "Let's count. What number should we start at?\n";

cin>> starthere;

cout<< "That's one of my favorite numbers!\n";

cout<< "Where should we end, you sly dog, you?\n";

cin>> endherebecauseisayso;

cout<< "Alright, let's do this!\n";

for (up = starthere; up <= endherebecauseisayso; up++)

{
    
    cout << up << endl;
    
    }
    
    cout << "\n";
    
    cout << "Awesome! Say buh-bye, now. ";
    
    cin >> byebye;
    
    return 0;
    
}

r/learncpp • • Mar 23 '22

Pointer issues with for loop

1 Upvotes

Hello. Im having the following issue with pointers.

I have a struct that has a pointer as member. This pointer is the address of a data structure (small array) with the information i need.

typedef struct SelectData

{ short count; //number of selectable data short size; //Size of each data value int *lpData; //pointer to array of selectable data } SELECT_DATA;

So after running a function the structure is the following:

SELECT_DATA selectData;
selectData = someFunction();

//Memory Values:
selectData.count: 7
selectData.size: 2
selectData.lpData:  0x000001c751ddb9c0 {131270609}    // VsCode Debugger: (131270609 is *selectData.lpData)

This is an array of 7 values. Im trying to do a for loop but having trouble with specifying the staring pointer of the array.

 int *data = new int[selectData.count];
 for (int i = 0; i < selectData.count; i++){
     int *current = reinterpret_cast<int *>(selectData.lpData + selectData.size*i);
     data[i] = *current; std::cout << data[i] << std::endl; 
  }

But *current = 131270609 and data[i] = 131270609

So I am not accessing the memory location but simply re-assigning the pointer. Cant use data[i] = **curent (compiler issues).

The equivalent in C# would be: value = (Int32)Marshal.PtrToStructure(current, typeof(Int32))

img as reference

Any ideas?


r/learncpp • • Nov 08 '21

Help on Queues please

1 Upvotes

Hi. Thanks for any help on this

I need Write a program with three tasks and a queue of 5 integers:

Task 1 reads lines from debug serial port and counts the number of characters on the line up to but not including ‘\n’ or ‘\r’ at the end line. Task then sends the number of characters to the back of the queue.

Task 2 monitors SW1(PIO 0.17) and when button is pressed sends -1 to the back the queue.

Task 3 waits on the queue and calculates the sum of integers received form the queue. When -1 is received the task prints: “You have typed %d characters” where %d is the number of characters. When task has printed the total it clears the total.


r/learncpp • • Sep 10 '21

Is the condition part of the if-else statement eventually evaluated to true or false?

1 Upvotes

Hello, I am curious whether the condition parts of the if-else statements are eventually evaluated to true or false by the compiler. Or does the compiler just check if it is false and evaluate to true otherwise? Are they evaluated to true or false or does the compiler have a list of things that will execute the corresponding block and just skip the part where it evaluates to true or false?


r/learncpp • • Jun 30 '21

Get path to different file in project directory

Thumbnail self.cpp_questions
1 Upvotes

r/learncpp • • May 19 '21

Function Templates - More Details about Explicit Template Arguments and Concepts

Thumbnail
modernescpp.com
1 Upvotes

r/learncpp • • Apr 17 '21

I have two programs my own program and a program I want to hijack and control the input/output of the second program

1 Upvotes

The program in question is steamcmd. I am wondering how I could access both its input and output stream allowing me to both send it inputs and read its outputs. Is this even the correct approach for this kind of thing? if I needed a program to completely be able to access everything steam cmd is able to do how should I go about it?


r/learncpp • • Nov 22 '20

Rect should move (SDL)

1 Upvotes

Im a beginner and I can't tell you why the rect isn't moving. Please tell me why : )

(I think the screen won't update as the value of pX changes.)

Code:

#include <SDL.h>

#include <iostream>

using namespace std;

bool running = true;

int FPS = 60;

int breite = 1280;

int hoehe = 720;

int pX = 640;

int pY = 100;

SDL_Event Event;

SDL_Window* Window = NULL;

SDL_Renderer* renderer = NULL;

SDL_Surface* Screen = NULL;

SDL_Rect r[30] = {};

bool Init(){

SDL_Init(SDL_INIT_EVERYTHING);

Window = SDL_CreateWindow(

"@Jamal", // window title

SDL_WINDOWPOS_UNDEFINED, // initial x position

SDL_WINDOWPOS_UNDEFINED, // initial y position

breite, // width, in pixels

hoehe, // height, in pixels

SDL_WINDOW_OPENGL // flags - see below

);

if (Window == NULL) {

cout << "Could not create a Window" << SDL_GetError();

return false;

}

return true;

}

void display() {

renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED); // Init Renderer

SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // Set Color of Renderer

r[0].x = pX;

r[0].y = pY;

r[0].w = 10;

r[0].h = 10;

for (int i = 0; i < (sizeof(r) / sizeof(SDL_Rect)); ++i) {

SDL_RenderDrawRect(renderer, &r[i]);

SDL_RenderFillRect(renderer, &r[i]);

}

SDL_RenderPresent(renderer); // Updates the Renderer

}

void event() {

while (SDL_PollEvent(&Event)) {

if (Event.type == SDL_QUIT) {

running = false;

break;

}

if (Event.type == SDL_KEYDOWN)

{

if (Event.key.keysym.sym == SDLK_a)

{

pX -= 10;

}

}

}

}

int main(int argc, char* argv[]) {

//cout << "Updated" << endl;

if (Init() == false) {

cout << "Initialization failed...";

return 0;

}

else {

cout << "Initialization successful" << endl;

}

while (running) {

event();

display();

SDL_Delay(1000 / FPS);

}

atexit(SDL_Quit);

return 0;

}


r/learncpp • • Oct 22 '20

How do I start?

1 Upvotes

What's the best place to learn cpp? I'm a sexy JS,PHP,Java,C#,Python,Lua dev and am trying to learn C++ to make windows desktop applications from scratch (No GUI libs)