Peter Goldbreaker Peter Goldbreaker - 3 years ago 217
C Question

Can bifields be compared, using <,>,=?

I am attempting to use a bit-field to store a series of counters that are being used to make triangles for graphics, since I only need values 0,1,2 for some of them and dont want to waste memory. What the code should do is start from bf.vertIndex = 0 and then loop through until bf.vertindex = 6 where it will stop running. However the program results in an infinite loop and when I have it print the value of bf.vertIndex as an int it is always = 1. Am I allowed to use bit-fields with these operands? and am I able to add an integer, such as 2, to the value of a given bitfield?

float vertexData[12];
triInfo bf;
count = 0;
bf.trinum = 0;
bf.addedx = 0;//tracks if the x cord needs to be offset = 1 or 0
bf.addedy = 0;//same as for the x cord
bf.vertIndex = 0;
//this loop should make a triangle
while (bf.vertIndex < 6){
//sets cordinates for a vertex
vertexData[bf.vertIndex] = 500 + width*(bf.addedx);
vertexData[bf.vertIndex] = 500 + height*(bf.addedy);
//keeps track of the number of vertices created and checks where if an
bf.vertIndex += 2;
if (bf.vertIndex = 2 && bf.trinum == 0){
bf.addedy = !bf.addedy;
}
if (bf.vertIndex = 4 && bf.trinum == 0){
bf.addedx = !bf.addedx;
}
cout << ((int)bf.vertIndex);

}


this is the way the bit field I used is laid out

struct triInfo
{
unsigned char trinum:1, addedx :1,addedy:1, vertIndex:5;

};


I saw a tutorial here Youtube where the gentleman making the video added two values together that were stored as chars at the point 10:15 in the video.

Answer Source

You can compare bit fields with <, >, and ==, just like any other integer. But = is an assignment, not a comparison, and you are inadvertently overwriting the value you are trying to compare.

If you are using clang or GCC, you should get in the habit of compiling with -Wall to enable compiler warnings, and then reading the warnings carefully so as to be able to fix the underlying cause. (Other compilers have similar mechanisms; consult the manual.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download