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

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.

Related

How to implement binary128 in C? [closed]

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 2 years ago.
Improve this question
I started to try and implement new data types, specifically floating-point values, using C. I came up with this sort of way on implementing binary128 using longer_int which I haven't fully understood.
The way how I started was to implement it via copying the code and modifying it. However, the code is C++, and C doesn't support OOP, so what I have to do is to try and translate the code.
I can't find the C version for longer_int because this question I once owned (the same account but now deleted) is now deleted and I can't view the links.
With the help of these C++ files, how can I implement binary128 using C?
And just so this question won't get closed, I want to know how to translate the OOP format in longer_int.h.
class longer_int {
private:
char num_str[];
public:
longer_int();
longer_int(const int &num);
longer_int(const char &num[]);
longer_int(const longer_int &num);
// Sample code from it, now translated to C, but still OOP
You should begin with something like this: a struct instead of a class, ignore the public/private keywords, the constructors are methods that return the my_int128. There is no overloading in C, so each different constructor must have a different name. Another school of thought would say that you don't need specialized constructors, but simply special method setters that can copy data from an int, from a char[] and from a my_int128 (and I prefer this school of thought). I give an example setter at the end.
#include <stdio.h>
#include <string.h>
typedef struct
{
char num_str[16]; /* fixed to int128 */
} my_int128;
/* Don't need this: my_int128 li = { 0 }; is enough!
my_int128 create_int128()
{
my_int128 li = { 0 };
return li;
}
*/
my_int128 create_int128_from_num(int num)
{
my_int128 li = { 0 };
/* TODO: set li with num */
return li;
}
my_int128 create_int128_from_char_array(const char num[16])
{
my_int128 li = { 0 };
memcpy(li.num_str, num, 16);
return li;
}
my_int128 create_int128_from_int128_ptr(const my_int128 *num)
{
return create_int128_from_char_array(num->num_str);
}
The setter:
void set_from_int(my_int128 *li, int num)
{
/* TODO: set li with num */
}
Your best shot using C would be implementing binary128 as a structure type
struct binary128 {
unsigned char data[16];
};
Mind that there is no operator overloading in C, so you will need to implement all interaction with the type (like assignment from another type, arithmetic operations, so on) as functions.
Follow link in comments posted by Shawn to see more general case: implementation of integers of arbitrary width.
I assume that you have some C++ object code and you want to rewrite it in plain C. Once you think that first C++ compilers were just pre-processors that generate C code, it should not be too hard.
First the caveats:
C has no provision for encapsulation: functions can only have translation unit visibility or global visibility
C has no provision for function overwriting. One function can only have one set of parameters: use different names
That being said, to translate a C++ class, you build a C struct to hold the data members, and replace methods with plain functions. For that last part, you just replace the hidden this with an explicit pointer as an additional parameter.

Is there anyway for the array at the end of class to work? [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 3 years ago.
Improve this question
I got an array at the end of my class and i don't know how to use it.
the bus[10] is so hard to understand. I don't know why it can access driver and what does empty() function really do.
#include "conio.h"
#include "stdio.h"
#include "iostream.h"
#include "string.h"
#include "graphics.h"
#include "stdlib.h"
#include "dos.h"
static int p=0;
class a
{
char driver[10];// driver
public:
void install();// for installing
}bus[10];//here we declare the number of buses we can have.
void a::install()
{
cout<<"Enter bus no: ";//ques
cin >> bus[p].driver;// what does this mean
bus[p].empty();//what does this mean
p++;
}
This is syntax for defining a type, and an instance of that type, at the same time.
For example:
struct Foo {} foo;
is the same as:
struct Foo {};
Foo foo;
So your example defines the type a, and also creates an array of 10 as called bus.
It would be more clearly written thus:
class a
{
char driver[10];
public:
void install();
};
a bus[10];
In this manner we can now more easily see that you've created a global array called bus, which you can use like you'd use any other array.
Since p is zero (to begin with), bus[p] just gives you the "first" a object in the array (to begin with). As p is increased, subsequent buses are accessed.
So, this:
cin >> bus[p].driver;
reads into the driver member of the pth bus.*
And this:
bus[p].empty();
means nothing, because a does not have a member function called empty().
* Well, the p+1th bus, because array indices begin at zero but English doesn't!
P.S. You can do funny (read: stupid) things with this syntax!
This is a very strange looking code, probably from an old workbook.
I could help you with achieving the action that you want, but it's hard to understand anything from this snippet.
Wrong: As far as I remember adding a identifier at the end of an unnamed struct gave it a name just like the usual approach.
struct {
float x, y;
} Point;
//is equal to
struct Point {
float x, y;
}
However I'm not familiar with the array syntax you provided.
I suppose std::cin >> bus[p].driver is meant to read the "name" that the char[10] driver field is. But using a char array here is troublesome and it's much better to replace it with std::string and shortening it to 10 characters after input.
The empty() method is often used as a container function returning boolean and telling the programmer whether the container is empty or not. Here however this function is undeclared and the code won't compile either way.
Not to mention that non-const variables placed out of function scope, like the static int p = 0, are a grave mistake.
Not true: In conclusion this is a very messy code and without the knowledge of what you want to achieve nobody could help you here.
See the answer below for better explanation.

Confused regarding this statement about "function call by reference."

What I'm confused about is whether the question is asking about passing arguments to functions as references (as opposed to "Call by Value") or about how we can set a pointer to point to a function.
The exact question is:
"Explain the function call by reference giving a suitable example in support of your answer."
The way it's termed makes it feel like it's asking about the latter. In my head, it seems as if it's asking how a function is called by reference, i.e, using a pointer.
C++ for what I'm talking about: int (*ptr)(int, int);
Which can later be assigned to a function like int max(int a, int b);
I know this is a bit of an odd post for Stack since it's more of an English question, but it's the only place I could think to ask.
EDIT: A lot of people are asking what I mean by the second thing. Since I'm new to the concept, I'll just copy - paste what my textbook gives as an example: (Sorry for the terrible formatting, sorry!)
main() {
int max(int a, int b){...}; //Your typical maximum function
int (*ptr)(int, int);
ptr = max;
//Then if you want to run the program
m = (*ptr)(2, 5);
cout << m; //Outputs 5
}

What is the difference between constant declaring Global or declaring inside a function where it is used [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i am declaring a constant (a large structure constant containing string) inside a function and it is used only inside this function.
will it have any execution time impact on my program? '
They will be created every time the function is called (take more time) or only once and the reference will be used through out its life.
If i declare the constant outside the function (global) will it be faster in execution ?
Actually, declaring variables inside of a function is a great practice. If that variable is only to be used inside of that function of course. There won't be any performance differences between the two methods, but making the constant global may require a more creative naming scheme while the one inside the function can be generic. It is only being used inside of that function, after all.
static struct can help you setting it up once and be done with it. This will be coming from data segment and initialise during at the startup. A raw and dirty code below, but will give you some intuition.
#include <stdio.h>
struct A {
int a;
int b;
};
void func(void)
{
static struct A a = {5,3};
printf("FUNC: A.a: %d\n", a.a);
}
int main(int argc, char **argv)
{
static struct A a = {6,4};
printf("MAIN: A.a: %d\n", a.a);
func();
return 0;
}
I would personally move it out of the function body if any other related functions use the variable, as long as you're using namespaces.
Also if its a true constant, I believe you can declare a struct static constexpr, which means that it won't be allocated on the stack every time the function is called (static), even if you declare it inside the function body. It also means that where it can be used at compile time, it will be (constexpr).
#include <iostream>
namespace Test{
struct Test {
char name[11];
int a;
int b;
};
static constexpr Test TEST_CONSTEXPR = {
"test value",
5,
6
};
}
int main()
{
std::cout << Test::TEST_CONSTEXPR.name << std::endl;
std::cin.get();
return 0;
}
In Ada this is compiler dependent. (As performance usually is.)
As "constants" are not compile-time static, a compiler may do the safe thing and evaluate the initialising expression every time the constant is declared.
If it really matters, measure what your compiler does.

Pointer vs Return [closed]

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.