Mathematic operations and structures in C

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
12 replies · 5K views
lewis198
Messages
95
Reaction score
0
Hello guys, I was wondering:

say you have a structure:

struct tag{

int a
char b
int b
int c
}

how would you make int c equal to int a + int b for all variables of type struct tag? I have tried using pointers but it baffles me how you would make a global change in that all variable s of type struct tag would be affected, rather than just specific variables.

thank you for your time.
 
Physics news on Phys.org
*variables rather than variable s
 
You'd have to perform the assignment t.c = t.a + t.b for every variable of type tag that you create. There is no such thing as a "global change."

If you decide to use C++ features, you can turn this structure into a class, and then use a member function to calculate c, rather than storing it directly.

- Warren
 
chroot said:
If you decide to use C++ features, you can turn this structure into a class, and then use a member function to calculate c, rather than storing it directly.

If you want to do that it would look like:

Code:
struct tag{

int a;
char b2;
int b;
int c() { return a + b; }
};

But remember, like chroot said, you cannot do this in C, you must be using C++; also did you notice you have two structure elements named "b"...?
 
oops, sorry-heehee!

but wow you can do that in c++, i'd better translate
 
would you have to declare a and b in the meber function c?
 
Hey guys I have a problem. When trying to compile this on dev c++ it wpon't let me, as it says I'm trying to make it a function, and when a change struct to a class, it says error before the class name, as well as calling 'private:' and 'public:' errors.
 
in fact, my devc++ compiler does not seem to accept any c++ language-when i enter count it says 'undeclared variable'. Do you guys know what the problem might be?
 
lewis198 said:
in fact, my devc++ compiler does not seem to accept any c++ language-when i enter count it says 'undeclared variable'. Do you guys know what the problem might be?

Did you say #include <iostream>?

If you put "using namespace std;" somewhere near the top of your file, does anything magic happen?
 
You mentioned "C", but you're trying to use a "C++" feature. If you want your source code to be compiled as "C++", the file name extension should be "cpp", not "c", such as "example.cpp" instead of "example.c".