Why my code is print for 4 in the line head? - c++

It is my code in the following instruction:
#include <iostream>
using namespace std;
class learning
{
public:
static int func(int var)
{
return var;
}
inline bool func(bool var=2 > 1)
{
bool& va = var;
int num = func(3);
num += va;
cout << num << " ";
return num;
}
};
int main()
{
learning len;
cout << "Testing " << learning::func(6) << " " << len.func();
return 0;
}
Why my cmd is print 4 Testing 6 1 but not is Testing 6 1 4?

I believe that what you are seeing is that the order of operator-arguments-evaluation is implementation-specific (at least prior to C++17). For further enlightenment, you might try running this program:
#include <iostream>
using namespace std;
static int DebugFunc(int i)
{
fprintf(stderr, "DebugFunc called with argument %i\n", i);
return i;
}
int main()
{
cout << DebugFunc(1) << DebugFunc(2) << DebugFunc(3);
return 0;
}
On my compiler (clang++/MacOS), the program outputs this (Note that the "DebugFunc called" lines are fprint()'ed to stderr rather than using cout, to avoid complicating the output of the cout line in main()):
DebugFunc called with argument 1
DebugFunc called with argument 2
DebugFunc called with argument 3
123
... which is reasonable, but I think MSVC is free to evaluate the arguments in a different order, and output e.g. this:
DebugFunc called with argument 3
DebugFunc called with argument 2
DebugFunc called with argument 1
123
If MSVC is evaluating the arguments from right-to-left, that would explain why your program's "4" is printed before its "Testing".

Related

Overloading << operator for printing stack in c++

#include <iostream>
#include <ostream>
#include <bits/stdc++.h>
using namespace std;
void printHelper(ostream& os,stack<int>& s){
if(s.empty())
return ;
int val = s.top();
s.pop();
printHelper(s);
os << val << " ";
s.push(val);
}
ostream& operator<<(ostream& os,stack<int>& s){
os << "[ ";
printHelper(os,s);
os << "]\n";
return os;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
stack<int> s;
for(int i = 0;i<5;i++){
s.push(i+1);
}
cout << s;
return 0;
}
// c++ stack -- push pop top size empty
I want to know as to why this code is not working, I want to print my stack in the same fashion as in java within square brackets i.e [ 1 2 3 4 5 ]. Please help me identify what have i done wrong.
The problem(error) is that printHelper expects two arguments but you're passing only when when writing:
//----------v--->you've passed only 1
printHelper(s);
To solve this(the error) just pass the two arguments as shown below:
//----------vv--v---------->pass 2 arguments as expected by printHelper
printHelper(os, s);
Working demo

Result of method used to call another method yields inconsistent results

I currently have to write a program that allows a user to pick between two objects to test.
This isn't the same program exactly but it's the same premise.
class defined by header file
#include <iostream>
class example {
private:
int x;
public:
example() {
x = 10;
}
void setNum(int input) {
x = input;
}
int getNum() {
return x;
}
};
Test main and selectObj method
#include <iostream>
#include "Header.h"
example selectObj(example A, example B) {
int selection;
std::cout << "Select object 1 or 2: ";
while (true) {
std::cin >> selection;
if (selection == 1)
return A;
else if (selection == 2)
return B;
else
std::cout << "Inavlid option, try again: ";
}
}
int main() {
example test1, test2;
selectObj(test1, test2).setNum(25);
std::cout << selectObj(test1, test2).getNum();
return 0;
}
selectObj is supposed to return an object. It runs but it isn't doing what setNum is supposed to do.
Suppose you choose option 1 for both calls of selectObj. It looks something like this.
Select object 1 or 2: 1
Select object 1 or 2: 1
10
It should have printed out 25 but instead, setNum isn't really changing the value of test1.
However, if I write
test1.setNum(25);
std::cout << test1.getNum();
Then it does indeed set test1's x value to 25.
Again, this isn't exactly like the program I had written (it is changed now and wouldn't like to rewrite that). However, it is an identical representation of the same concept.
The problem is that you're passing and returning the arguments by value instead of reference. To solve this you can pass and return the arguments by reference as shown in the below modified code:
main.cpp
#include <iostream>
#include "Header.h"
//return and pass by reference
example& selectObj(example &A, example &B) {
int selection;
std::cout << "Select object 1 or 2: ";
while (true) {
std::cin >> selection;
if (selection == 1)
return A;
else if (selection == 2)
return B;
else
std::cout << "Inavlid option, try again: ";
}
}
int main() {
example test1, test2;
selectObj(test1, test2).setNum(25);//this sets the value of x member of the object that the user chooses
std::cout << selectObj(test1, test2).getNum();
return 0;
}
The output of the above program when the user enters option 2 is:
Select object 1 or 2: 1
Select object 1 or 2: 1
25

How does the condition (Expression-2) of this for loop work?

#include <bits/stdc++.h>
using namespace std;
int fun()
{
static int num = 16;
return num--;
}
int main()
{
for(fun(); fun(); fun())
cout<< fun()<<" ";
return 0;
}
Output : 14 11 8 5 2
How does the condition (expression-2) of the for loop work? I mean, why does it terminate when fun returns 0 (num becomes -1)?
The condition statement is evaluated before entering the body of the loop. In your case, the statement evaluates to true, and the loop body is executed, if fun() returns a non-zero value.
To see this clearly, modify your code as follows:
int fun( const char* name)
{
static int num = 16;
cout << name << ":" << num << "\n";
return num--;
}
int main()
{
for(fun("init"); fun("test"); fun("iterate"))
cout<< fun("body")<<" ";
return 0;
}

Function must return a value

I am trying to make a text based RPG and i'm fairly new to c++. I understand that I need to return a value, but when I try and return CharacterName or CharacterRace it comes up with unresolved externals errors. I'd really appreciate the help guys, thanks :)
CharacterCreation.h
#include <string>
#include <iostream>
void petc(), ConsoleClear(), petc(), EnterClear();
std::string CharacterName, CharacterRace;
Main.cpp
#include <iostream>
#include <limits>
#include <string>
#include <string.h>
#include "CharacterCreation.h"
std::string CharacterCreation();
int main()
{
CharacterCreation();
}
std::string CharacterCreation(int RaceChoice, int RaceChoiceLoop)
{
RaceChoiceLoop = 0;
std::cout << "Welcome to the character creation V 1.0.0" << std::endl;
EnterClear();
std::cout << "Choose a name: ";
std::cin >> CharacterName;
std::cout << CharacterName << std::endl;
EnterClear();
while (RaceChoiceLoop == 0)
{
std::cout << "(1) Human - Human's race perks: + 5 to Magic | + 1 to Sword Skill" << std::endl;
std::cout << "(2) Elf - Elve's race perks: + 5 to Archery | + 1 to Magic" << std::endl;
std::cout << "(3) Dwarf - Dwarven race perks: + 5 to Strength | + 1 to Archery" << std::endl;
std::cout << "Choose a race, " << CharacterName << ": ";
std::cin >> RaceChoice;
if (RaceChoice == 1)
{
RaceChoiceLoop = 1;
CharacterRace = "Human";
}
else if (RaceChoice == 2)
{
RaceChoiceLoop = 1;
CharacterRace = "Elf";
}
else if (RaceChoice == 3)
{
RaceChoiceLoop = 1;
CharacterRace = "Dwarf";
}
else
{
std::cout << "Invalid Option";
EnterClear();
RaceChoiceLoop = 0;
}
}
}
void petc()
{
std::cout << "Press Enter To Continue...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
void EnterClear()
{
std::cout << "Press Enter To Continue...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
system("cls");
}
void ConsoleClear()
{
system("cls");
}
A declared std::string function should return a string and this is not the same as printing it on the screen, use return "something" inside the function otherwise declare it void.
The "unresolved externals" message isn't directly caused by your returning a value.
It's a linker error, and only occurs because compilation succeeded.
The cause is that you're declaring, and calling, this parameter-less function:
std::string CharacterCreation();
but you're defining this function with two parameters:
std::string CharacterCreation(int RaceChoice, int RaceChoiceLoop)
The declaration and the definition must match.
From the looks of it, you don't actually want the parameters and should use local variables instead:
std::string CharacterCreation()
{
int RaceChoice = 0;
int RaceChoiceLoop = 0;
// ...
Problem is that the function CharacterCreation() (taking no arguments) is never defined, and thus the linker cannot find it.
Try substituting in the following:
std::string CharacterCreation(int, int);
int main()
{
CharacterCreation(1,1);
}
This will call the CharacterCreation function you have implemented below the main function. Doing this I can compile (and link) your code :)
As I have pointed in my comment before, your CharacterCreation method does not return any value, although you have defined a string as an expected one.
What you most likely want to do is either change CharacterCreation signature to:
void CharacterCreation(int RaceChoice, int RaceChoiceLoop)
and keep the current implementation
or pack all your console output in a string and return it at the end of the method.
Then in main()
string result = CharacterCreation();
can retrieve this value and you can print it in main

Programming error in C++

I recently started learning C++ but I came across a problem. The program given below is not giving me the desired result as I only see 'Hi' in the result but not what's written in the void function. Please tell me the reason that this is happening along with the solution.
I am using Xcode 6.3.1 and the I have selected the language C++.
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
void ABC ();
return 0;
}
You are redeclaring a void ABC() function inside main(). Just call ABC(); without the void.
You can take a look at this question about declaring a function within the scope of another.
In your code your function call was wrong.
When you call your function you don't need to add the return type:
#include
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC ();
return 0;
}
you need to call your method and not declare it inside main
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}
EDIT 1:
Since you started learning C++ i recommend the following recommendations to make sure your code is cleaner. Please note , these are not rules by any mean , but more of best practices and a style of coding.
Use meaningful names for your variables, methods, functions , classes
... So instead of ABC() name it something that if you (or someone
else is reading it) will now what it suppose to do.
When calling methods and functions try to declare them with the
appropriate returning value. Void by definition doesn't return any
value it just process the code inside of it. so your methods/function
should return appropriate values of do what it suppose to.
Here's version 2 of your code with examples of 3 different methods and calls:
#include <iostream>
using namespace std;
int sum;
string MethodReturningString()
{
return "Hey there i am the result of a method call !";
}
int MethodReturningInt()
{
return 5;
}
void CalculateSum(int x,int y)
{
sum=x+y;
}
int main()
{
cout << MethodReturningString() << endl;
cout << MethodReturningInt() << endl;
cout << "Calculating sum:" ;
CalculateSum(5,4);
cout << sum << endl;
return 0;
}
Happy coding
In C++, like pretty much any other language, you do not specify the return type when calling a function. So change the line that reads:
void ABC ();
to:
ABC();
Try this:
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC();
return 0;
}
You should call a function simply by stating its name and adding parentheses.
instead of using void ABC() for calling the function ABC() in main(), use the following code:
#include
void ABC ()
{
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}