Pointer vs Return [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Which is faster when assigning a variable via a method, to return a variable, or to point to a variable?
Case 1:
Function Declaration
void foo(int* number)
{
*number = 5;
}
Usage
int main()
{
int number;
function(&number);
cout << "Number: " << number;
}
Case 2:
Function Declaration
int foo()
{
int number = 5;
return number;
}
Usage
int main()
{
int number;
number = function();
cout << "Number: " << number;
}
PS: In case 2, I created a variable and returned it instantly. I know this doesn't make sense, but this is the closest example I can find for the situation I'm dealing with, since I'm initializing an actual object, which requires creating the object first, editing it, then returning it

It depends on the cost of copying the variable. For primitive types, return a value.
For more complex types consider passing in a reference, or take a look at the C++11 move semantics.

One benefit of using output parameters (Case 1) is it gives you the ability to have a function 'return' multiple values:
void foo (int* x, int* y)
{
*x = 5;
*y = 4;
}
But like everyone said in the comments, this doesn't matter in C++ as much as C.
Generally returns are far more readable and make your program's logic well defined and
easy to follow. In C++, stick to returns or references.

Typically, you should choose which to use on your needs rather than on performance.
Do you have multiple outputs? -> Use pointers
Is an input going to be an output -> Might as well use pointers
It's more difficult with these two scenarios to return a variable.
Other than that, performance-wise, it's only nice to use a variable when the variable is super complex, that way, you're only passing in a pointer instead of that super complex object. But any performance gain is negligible other than that.

Related

Is it okay if we assign const integer a value like this? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I wanted to assign a value to a constant but as it is constant, we cant assign value to it through cin. So I came up with this idea. Is it okay if we use it like this?
{
int data = 0;
cout << "enter number of students"<<endl;
cin>>data;
const int number = data;
cout << number<<endl;
}
This is fine. const values do not need to be compile time constants. They just can't be changed after they are defined.
Similarly you could do:
int getNumberFromStdin() {
int data;
cin >> data;
return data;
}
int main() {
const int number = getNumberFromStdin();
}
Yes, because it is not an assignment; it is a declaration.
Despite looking quite similar, the two constructs are different: assignment changes something that is already declared, while the declaration sets up something new, and optionally gives it a value. The value does not need to be hard-coded, though: it can be a result of some processing, as is the case in your example.
Naturally, assignment is not allowed for constants, because they already have a value.

Should I use the 'const' keyword in c++ [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am new to C++ and have come across the const keyword. I looked it up online and read that The main use is to prevent the changing the value throughout the program. I have these two snippets below
const int size = 56;
Compared to using
int size = 56;
Why should I use one over the other? What is the idea behind using it.
Yes, you should make all variables const if you are never going to change its value after initialization. This prevents bugs where you accidentally change a value you're not supposed to. You seem to be aware of this already.
In addition, there is something that you might not be aware of, which is that making an int variable const also makes it a constant-expression, so long as the initializer itself is also a constant-expression, e.g. the int literal 56. This allows you to use it in contexts where you need a constant-expression, e.g. as the dimension of a static array:
const int size = 56;
int a[size]; // ok
int size = 56;
int a[size]; // error
In c++ CONST is used when you want to declare something which will not change its value throughout the program. But if you accidentally try to rewrite its value, the compiler will through an error. Most of the time it is recommended to declare a variable of int type so you can redefine its value when it's required. CONST is used when you want to declare a static array i.e.
const int a = 100;
int sampleAray[a];
And int is used when you, the value of the variable will be modified at some point i.e.
int a = 12;
int arr[4] = {11,22,33,554};
for (int i=0; i<4; i++){
if(arr[i]%2 == 0){
a+=arr[i];
}
}
When you have a const variable holding something that should not change and accidentally write code that modifies the variable anyway, you get a nice compiler error and can correct your mistake easily. If the variable is non-const, the compiler cannot help you and you now have a bug that may be hard to find.

Why does C++ allow nested namespace with same name? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Codes bellowing compiles:
namespace x
{
namespace y
{
namespace x
{
struct C
{
C ()
{
std::cout << "x::y::z::C" << std::endl;
}
};
}
}
struct C
{
C ()
{
std::cout << "x::C" << std::endl;
}
};
}
x::C and x::y::x::C are not same, but it's sometimes confusing.
Why is x::y::x allowed in C++? Isn't it more clear to forbid this?
Why is x::y::x allowed in C++? Isn't it more clear to forbid this?
No offense, but I think your premise is seriously flawed.
Maybe you didn't notice but having names being the same on different levels of nesting is something very natural. Consider constructors. The fully qualified name of a constructor of class foo is foo::foo(). Nothing unusual is it?
Now what if I want to put my class inside a namespace called foo. I am not arguing that this is the best naming scheme, but from the top of my head I also see no reason to outright forbid it. The constructor would be foo::foo::foo() then.
Having a rule that would disallow such naming would lead to lots of frustration to anybody that wants to use such (possibly suboptimal, but thats just opinions) naming scheme while having absolutely zero gain for someone that does not want to use such naming. In total there would be no benefit.
It's similar to variables having the same name in different scopes. Technically valid. After all, at the assembly level there are no names, just pointers and sizes.
void foo()
{
int x = 1;
if (true)
{
int x = 2;
x = 3; // Whops
}
}
C++ is not a forgiving language, if you mess up with anything, including variables naming, you are on your own. If you want the language to save you, there are (plenty of) other languages to pick.
That said, MSVC (and probably other compilers) issues a warning when a declared variable hides another variable in an outer scope, so by reading compiler warnings you can be helped.

Getting Array from Another class C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am making a simple Lottery program - and am struggling with implementation. I have a class called 'Ticket Line' this class simply holds 6 numbers that the player is playing a lottery for.
What I want to do, is generate 6 randomly (got function for this already) and then store that in another class as values. To do this, I am using the following code:
class Draw
{
private:
int drawID;
TicketLine* DrawnNumbers;
bool drawn;
}
When a Draw is completed I want to generate the Random Numbers ( from the TicketLine class) and then for the Draw to be able to store those numbers into its Draw File.
How would I be able to access the functionality of the DrawnNumbers class - and store the results from the getTicketNumbers.getTicketLine()function.
int* getTicketNumbers(void) { return DrawnNumbers->getTicketLine();};
The program crashes the following code:
//int *ptr[6] = getTicketNumbers();
int *ptr[6] = getTicketNumbers();
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
TicketLine class:
private:
int select[6]; //Array of Ticket Numbers.
int* getTicketLine(void) { return select; };
I am willing to offer a couple of virtual beers to the solution. I am as yet to find a good online pub - if you know of one then please do let me know :-)
Thanks,
Without knowing any more, this line:
int *ptr[6] = getTicketNumbers();
is very suspect.
Why? Well, we haven't seen the implementation of getTicketNumbers so we don't know if it's actually allocating memory for 6 and returning such an array.
Also, you are printing the values of pointers here:
for (int x = 0; x < 6; x++){
cout << ptr[x];
}
Where, if you intended to actually print the int values, you'd say something like this:
for (int x = 0; x < 6; x++){
cout << *(ptr[x]);
}
My guess is that you are either:
Going out of bounds of an array that was (not) allocated, or,
Modifying actual pointer values somewhere instead of the integers they point to (as indicated by your lack of dereferencing ptr[x] in your print statement)
Edit
With more information, it seems you probably meant to say this:
int *ptr = getTicketNumbers();
instead of this:
int *ptr[6] = getTicketNumbers();
You should probably be doing some sanity checks as well to make sure that select is actually filled before calling that function (maybe giving it a default value of {0,0,0,0,0,0} in the constructor)
DrawnNumbers doesn't appear to be pointing to anything yet. It's a pointer, but to what?
Also, be careful about returning arrays that way. If the object or stack frame that the array resides in goes away, you'll be left pointing to bad things.

Changing the value of an attribute dynamically in cpp [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a struct :
struct Person{
int scoreone;
int scoretwo;
int scoretotal;
}
main(){
Person a;
a.scoreone=3;
a.scoretwo=5;
//and later
a.scoreone=10;
}
I want the scoretotal to be updated when scoreone and scoretwo are chnaged without using any function.
Thanks
That can't be done in C++. The C++ way to handle this is to convert scoretotal to a method
struct Person{
int scoreone;
int scoretwo;
int scoretotal() { return scoreone + scoretwo; }
};
Now instead of saying person.scoretotal you say person.scoretotal() and the score total will be recalculated each time.
Can't be done--to change a value automatically, you need to run some code, and (in either C or C++) code is always in a function.
The rest of this answer assumes the use of C++, and won't work in C at all.
You can, however, keep the fact that it's a function from being externally visible, which (I'd guess) is what you care about:
struct Person {
int scoreone;
int scoretwo;
class total {
int *a, *b;
public:
total(int *a, int *b) : a(a), b(b) {}
operator int() { return *a + *b; }
} scoretotal;
Person() : scoretotal(&scoreone, &scoretwo) {}
};
This does have a (usually minor) side effect. It depends upon an implicit conversion from Person::total to int to do its job. That can lead to unexpected results in a couple of situations. One would be if you're trying to use some_person.scoretotal in a situation where you expect an implicit conversion from int to some other type. You're already using an implicit conversion from Person::total to int, and the compiler will only use one user-defined conversion implicitly, that would fail. In the other direction, if you were to use auto x = some_person.scoretotal;, x would be a Person::total rather than an int, because auto would deduce the actual type without the implicit conversion happening.
As long as you do relatively obvious things like:
Person some_person;
some_person.scoreone = 1;
some_person.scoretwo = 2;
int total = some_person.scoretotal;
std::cout << "Total score: " << some_person.scoretotal;
...you'll get scoretotal tracking the total of scoreone and scoretwo without making it obvious that a function has to be invoked to do that.
Irrespective of the language that you are using, the fundamental problem is in the design of your struct. There are only two independent data values in this structure. But you are storing three. That is the mistake.
What you need to to is store just the two primary values, scoreone and scoretwo. Those are the data. The other value is a derived value defined by the relationship that the total is equal to the sum scoreone + scoretwo.
So you should remove the data member scoretotal and replace it with a function if you are coding in C, or a member function if you are coding in C++. In C the code might look like this:
struct Person{
int scoreone;
int scoretwo;
};
int scoretotal(const struct Person person)
{
return person.scoreone + person.scoretwo;
}
If you declare struct Person the way john did in his answer you should not get an error when calling the scoretotal function. Remember to include the parentheses, saying "person.scoretotal" won't work, you have to write "person.scoretotal()" because you're calling a function in the Person-struct, not asking for a member.