Question about the efficiency of using an array or individual variables

Click For Summary
SUMMARY

The discussion centers on the efficiency of using boolean arrays versus individual boolean variables in C++. The consensus is that accessing individual variables (B0 to B9) is faster due to direct memory addressing, while accessing array elements (A[0] to A[9]) requires address calculation, which introduces overhead. Additionally, the initialization of boolean arrays requires explicit initialization for each element, as a single initializer only sets the first element. The conversation also touches on the limitations of static arrays and the advantages of using dynamic arrays, such as std::vector, for user-defined sizes.

PREREQUISITES
  • Understanding of C++ boolean data types
  • Familiarity with array and vector data structures in C++
  • Knowledge of memory addressing and performance implications
  • Basic understanding of C++ initialization rules for arrays
NEXT STEPS
  • Explore C++ memory management techniques, including dynamic allocation with new and delete
  • Learn about the performance characteristics of std::vector compared to static arrays
  • Investigate C++ initialization techniques for arrays and the implications of default initialization
  • Study the impact of cache memory on data access patterns in programming
USEFUL FOR

Software developers, particularly those working with C++ and focusing on performance optimization, as well as students learning about data structures and memory management in programming.

  • #61
One reason for code bloat is the use of libraries that do what you want and more. Unfortunately, sometimes you can't just discard the more part.

One example from my recent past is developing code in python using Anaconda. Python modules call in other python modules so while you may want some particular function in a given module. It will pull in other modules you don't need.

The upside of using other peoples code is that you don't have to write it only use it as it probably had better testing done depending on its maturity of course.

We code to fit into the hardware we have and if we need a lot less memory then it can be engineered out of the final product. But wait, we may need to patch or update the code and we may need that memory that was removed so we must balance out our tradeoffs.

The old programming mantra still holds:
_ I can make it fast
- I can make it cheap
- I can make it reliable

pick any two and let me know.

Of course, bosses today will pick two and then ding you on the one they didn't choose.

Its good that you have an engineering background but sometimes that will get in the way of software development.

On one project I worked on, the engineers saved money on a signal pattern generator for high speed memory testing by packing the internal looping code ie by using 14 bit counters in one place and 12 bit in another...

It was a bear for programmers to build loop code loads as we had to constantly pack stuff up and decode errors returned to figure out what was happening during a test.

The hardware design didn't factor in the programmer's needs in the interest of getting the cheapest and fastest hardware possible.

I remember one hardware manager showing empathy to the programmers by saying he once wrote a BASIC program and can understand the difficulties we faced. We just looked at each other.

Some of the engineers in our group looked down on the programmers too. We needed to test a C based monitoring program that handled 200 sensors in a bay continuously for a few days. However, every morning we discovered it was swapped out for a PC BASIC program.

When asked why the engineers said our program ran too slow for their needs. Upon further investigation, we discovered that their program ran faster because it monitored only 20 sensors continuously. What a crock? Ours was configurable and could have done the same if they told us.

The payback came when they had some test program written in BASIC that exceeded 64K (PC-DOS BASIC limit) and they wanted our help to fix it. We suggested removing comments and other memory saving tricks but to no avail. Finally we said well I guess you'll have to recode it in C like we told you months ago. They were not happy campers after that.
 
Technology news on Phys.org
  • #62
Ha, I never told programmers what to do, they tell me what they need and I design to fit their needs! They are the one that have to make the system work, Hardware part is only to support the system. Unless it is impossible for us to meet their needs, I always try to give them what they want. I sure did not tell them what language to write! What do I know!

I did a little assemble language programming long time ago, at least I know enough how to design hardware to make lives easier for people that are going to program it. Remember, we can make the most reliable hardware, but if programmer cannot program it, it's still a big fat ZERO. So part of my task is to make programmers' lives easier if all possible. It was always very smooth, never ran into problem in that department.

My specialty is really analog, RF, low noise. I had to design MPU digital stuffs only because I was the only one that can do it. It's not like I did those every day. Just design when needed. I designed the hardware, wrote the specifications how to program it. Never once I heard back from the software people after I handed it over. Maybe I was lucky!
 
  • Like
Likes jedishrfu
  • #63
Back to the original question, is there any way to fix using function
void getnumSold( vector<int>&numSold) and use vector<int>numSold(DefaultNSold) to copy DefaultNSold into numSold and then allow main to access as reference?

thanks
 
  • #64
yungman said:
So there is no fix on this other than quit using vector<int>set1(set2) with function passing vector as reference? This is NOT about hitting screw with hammer, it's a matter either I did something wrong that I don't know, or something is wrong with the that line. I know one can NOT pass parameter without declaring
void getnumSold( vector<int>&numSold). Also one has to write vector<int>numSold(DefaultNSold) in order to copy from DefaultNSold into numSold . So this is catch 22. I know this is a problem. How do people solve this?

What you did wrong is exactly what the error message said.

Also one has to write vector<int>numSold(DefaultNSold) in order to copy from DefaultNSold into numSold . So this is catch 22. I know this is a problem. How do people solve this?

What that does is not just copy. It is making a whole new vector, numSold (using the same name as the parameter, hence the error message). I think your confusion will be cleared up when you learn about classes. You didn't learn what a constructor is yet, and were using it without even knowing it, thinking it was something else.

Anyways, I guess this is what you wanted to do (use the assignment operator):

Code:
void getnumSold(vector<int>& numSold)
{
    numSold = DefaultNumSold;
}

Also, it might be a good time to do a google search: "why are global variables considered bad programming practice".
 
Last edited:
  • #65
I put in the line you suggested, it's NOT working, it won't even compile. Also, I specifically asked about how to use vector<int>numSold(defaultNSold) for copying. I know numSold was defined TWICE, one in the function declaration, one in vector<int>numSold(defaultNSold). But this is how the syntax has to be. I am not asking about the error information. I know what is the error. My question is HOW to fix it using vector<int>numSold(defaultNSold).

This is what you suggested, it won't compile. I know how to fix the problem and I already fixed it using simple for loop.
C++:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&);
vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    char key = 'A';
    vector<int>Sold(DefaultNSold.size());//receive number sold for each item.
    getnumSold(Sold);//passing vector Sold to function getnumSold().
    count << "In main return from getnumSold Sold = {";
    for (int i = 0; i < 9; i++)
        count << Sold[i] << " ";
    count << "} \n\n";
    return 0;
}void getnumSold(vector<int>& numSold)
{
int row = 1;

    numSold = DefaultNumSold;

count << " In getnumSold, You chose to use default = {";
for (row = 0; row < DefaultNSold.size(); row++)
{
    count << DefaultNumSold[row] << " ";
}
count << numSold[row] << "}\n\n";

}
 
  • #66
yungman said:
Because my syntax was not wrong.

I figured that much already.So there is no fix on this other than quit using vector<int>set1(set2) with function passing vector as reference? This is NOT about hitting screw with hammer, it's a matter either I did something wrong that I don't know, or something is wrong with the that line. I know one can NOT pass parameter without declaring
void getnumSold( vector<int>&numSold). Also one has to write vector<int>numSold(DefaultNSold) in order to copy from DefaultNSold into numSold . So this is catch 22. I know this is a problem. How do people solve this?I want row to represent the real row number. The way I do works.
yungman said:
I put in the line you suggested, it's NOT working, it won't even compile. Also, I specifically asked about the code vector<int>numSold(defaultNSold) for copying. I know numSold was defined TWICE, one it the function declaration, one in vector<int>numSold(defaultNSold). But this is how the syntax has to be. I am not asking about the error information. I know what is the error. My question is HOW to fix it using vector<int>numSold(defaultNSold).

This is what you suggested, it won't compile.
C++:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&);
vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    char key = 'A';
    vector<int>Sold(DefaultNSold.size());//receive number sold for each item.
    getnumSold(Sold);//passing vector Sold to function getnumSold().
    count << "In main return from getnumSold Sold = {";
    for (int i = 0; i < 9; i++)
        count << Sold[i] << " ";
    count << "} \n\n";
    return 0;
}void getnumSold(vector<int>& numSold)
{
int row = 1;

    numSold = DefaultNumSold;

count << " In getnumSold, You chose to use default = {";
for (row = 0; row < DefaultNSold.size(); row++)
{
    count << DefaultNumSold[row] << " ";
}
count << numSold[row] << "}\n\n";

}
What you are saying doesn't make any sense.
 
  • #67
Jarvis323 said:
What you are saying doesn't make any sense.
This is what you suggested to do: numSold = DefaultNumSold; It won't even compile.

I am not asking HOW to copy the vector from DefaultNSold to numSold, there are ways to do that. I specifically asked about using vector<int>numSold(defaultNSold) line to copy when passed to the function. This is in the book. It works if it is not passing into a function.

I already use a simple for loop to copy and completed the program already.

 
  • #68
yungman said:
This is what you suggested to do: numSold = DefaultNumSold; It won't even compile.

I am not asking HOW to copy the vector from DefaultNSold to numSold, there are ways to do that. I specifically asked about using vector<int>numSold(defaultNSold) line to copy when passed to the function. This is in the book. It works if it is not passing into a function.

I already use a simple for loop to copy and completed the program already.

If you read the error message of the new code where you used the assignment operator, you'll see that this is the error message.
Code:
prog.cpp:26:15: error: ‘DefaultNumSold’ was not declared in this scope
     numSold = DefaultNumSold;

It's because I wrote DefaultNumSold instead of DefaultNSold.

yungman said:
I specifically asked about using vector<int>numSold(defaultNSold) line to copy when passed to the function. This is in the book. It works if it is not passing into a function.

I already use a simple for loop to copy and completed the program already.

Like I said, that doesn't make sense at all. It isn't code for copying like you think it is, read my previous post again. Your problem is you don't understand what the line of code means. Once you understand what that code means, you'll realize your mistake and that it has nothing to do with it being passed to a function or not. Here is an equivalently wrong program without a function.

Code:
vector< int > x;
vector< int > &  y = x;
vector< int > y = default;

You need to slow down and learn what the code you are writing actually means, not just what you expect it to do.
 
Last edited:
  • Like
Likes pbuk
  • #69
Jarvis323 said:
Like I said, that doesn't make sense at all to do. Your problem is you don't understand what the line of code means, which I explained to you. Once you understand what that code means, you'll realize your mistake. It has nothing to do with it being passed to a function or not. Here is an equivalently wrong program without a function.

Code:
vector< int > x;
vector< int > &  y = x;
vector< int > y = default;
Jarvis323 said:
I understand the lines of code, I need to define the function
void getnumSold(vector<int>& numSold)

AND

I have to follow the instruction from the book vector<int>numSold(defaultNSold)

That defined the vector twice and thereby have the error. BUT I experimented the line of code vector<int>numSold(defaultNSold), it works as long as it's not passed to function. It WON'T work when passing the function.

These are very specific syntax and they don't work together. My question is how can I make this work. NOT how to do it.
 
  • #70
You can't make it work because it doesn't make any sense. If you want a new variable, then just use a different name. It won't be the same variable of course. It doesn't make a difference whether it's inside a function or not, you can't use the same name for two different variables. If it worked for you outside a function, then that's not what you did. Here are some examples.

C:
// this is wrong
vector< int > x;
vector< int > &  y = x;
vector< int > y( d ); // the name y is already used

// this is also wrong
vector< int > x;
vector< int > x; // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x( d ); // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x = d;// the name x is already used

// this is correct
vector< int > x = d;

// this is correct and exactly equivalent to the last version
vector< int > x (d);

// this is correct as well
vector< int > x;
x = d;

And it's not because it's a vector either.

C:
// this is wrong
int x;
int &  y = x;
int  y( d ); // the name y is already used

// this is also wrong
int x;
int x; // the name x is already used

// this is also wrong
int x;
int x( d ); // the name x is already used

// this is also wrong
int x;
int x = d;// the name x is already used

// this is correct
int x = d;

// this is correct
int x (d);

// this is correct as well
int x;
x = d;
 
Last edited:
  • #71
Jarvis323 said:
You can't make it work because it doesn't make any sense. If you want a new variable, then just use a different name. It won't be the same variable of course. It doesn't make a difference whether it's inside a function or not, you can't use the same name for two different variables. If it worked for you outside a function, then that's not what you did. Here are some examples.

C:
// this is wrong
vector< int > x;
vector< int > &  y = x;
vector< int > y( d ); // the name y is already used

// this is also wrong
vector< int > x;
vector< int > x; // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x( d ); // the name x is already used

// this is also wrong
vector< int > x;
vector< int > x = d;// the name x is already used

// this is correct
vector< int > x = d;

// this is correct and exactly equivalent to the last version
vector< int > x (d);

// this is correct as well
vector< int > x;
x = d;

And it's not because it's a vector either.

C:
// this is wrong
int x;
int &  y = x;
int  y( d ); // the name y is already used

// this is also wrong
int x;
int x; // the name x is already used

// this is also wrong
int x;
int x( d ); // the name x is already used

// this is also wrong
int x;
int x = d;// the name x is already used

// this is correct
int x = d;

// this is correct
int x (d);

// this is correct as well
int x;
x = d;
I know what you are talking all along. I cannot make it work because the code vector<int>numSold(defaultNSold) cannot work in all situation, maybe that's answer to my question already, I cannot use this to copy vector in the function where I have to define the vector in the function parameters.
 
  • #72
yungman said:
I know what you are talking all along. I cannot make it work because the code vector<int>numSold(defaultNSold) cannot work in all situation, maybe that's answer to my question already, I cannot use this to copy vector in the function where I have to define the vector in the function parameters.
No. It has nothing to do with functions or function parameters, or vectors, or copying. It's much much simpler and the same in every single case. You cannot declare two completely separate variables with the same name in the same scope. It's exactly the same reason you cannot do, int x; int x;, it's not that you cannot use int x; in some special case, it's that the name is already used. You can't do it in any case. Again, the copy constructor is not a copy function. It creates a another variable that is initialized based on the value of the other one.
 
  • #73
Here is an analogy that hopefully makes sense.

You go and buy a blender. You read the instructions. It says, to use the blender:

1) unpack the blender from the packaging
2) plug it in
3) press the on button

Later on, after you've already unpacked it and have used it once, you decide to move the blender into a new room. And then you want to turn it on. You read the instructions again, how to turn it on. But you find you cannot (1) unpackage the blender, because the packaging is gone. So your solution is you go to the store, buy a new blender, unpack that one, plug that one in, and press its on button. But the old blender is still not on. So you complain. How can I make my old blender work by buying a new blender, unpacking it and turning it on?

The answer is you can't, it's a different blender. The solution is to just plug the old blender in, and it doesn't make sense to unpack and already unpacked blender.
 
  • #74
Jarvis323 said:
Here is an analogy that hopefully makes sense.

You go and buy a blender. You read the instructions. It says, to use the blender:

1) unpack the blender from the packaging
2) plug it in
3) press the on button

Later on, after you've already unpacked it and have used it once, you decide to move the blender into a new room. And then you want to turn it on. You read the instructions again how to turn it on. But you find you cannot (1) unpackage the blender, because the packaging is gone. So your solution is you go to the store, buy a new blender, unpack that one, plug that one in, and press its on button. But the old blender is still not on. So you complain. How can I make my old blender work by buying a new blender, unpacking it and turning it on?

The answer is you can't, it's a different blender. The solution is to just plug the old blender in, and it doesn't make sense to unpack and already unpacked blender.
I know, it won't work. That's my conclusion already.
 
  • #75
I finally finish the program using the dumb way to copy vector. Works like a champ. I made it a lot fancier, instead of following the book use given set of number sold for each product, I can input the numbers as wish by user. then display the description, price, #sold and total dollar sold for each item and sort with the highest dollar amount first.
C++:
// This program display the title of the product, the unit cost and the total sales in 6 months
// And sort in the order of the highest dollar sales product first to the least.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

void getnumSold(vector<int>&); //To input the number of unit sold in 6 months, you can choose to input the number or use default.
void displayProd(vector<int>&, vector<float>);//displace the list of product and their cost.
void DollarSales(vector<int>&, vector<float>&);//Calculate the total dollar sold for each item.
void sortSales(vector <float>, vector<int>&);// Sort with highest dollar sold first.
void displaySales(vector<int>, vector<float>, vector<int>);// Display in order of the highest dollar sold first.const int Row = 9, ProdCol = 31;
char Prod[Row][ProdCol] = { {"(0)Six Steps to Leadership"}, {"(1)Six Steps to Leadership"}, {"(2)Road to Exellence"},
                {"(3)Seven Lessons of Quality"},{"(4)Seven Lessons of Quality"},{"(5)Seven Lessons of Quality"},
                {"(6)Teams Are Made, Not Born"}, {"(7)Leadership for the Future"}, {"(8)Leadership for the Future"} };

char Desc[Row][ProdCol] = { {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Audio CD"}, {"DVD"},
                {"Book"}, {"Book"}, {"Audio CD"} };

float Price[] = { 12.95, 14.95, 18.95, 16.95,
                21.95, 31.95, 14.95, 14.95, 16.95 };

int pnAr[] = { 914, 915, 916, 915, 918,//   0, 1, 2, 3, 4
              919, 920, 921, 922 };//        5, 6, 7, 8

vector<int>DefaultNSold = { 842, 416, 127, 514, 437, 269, 97, 492, 212 };

int main()
{
    vector<int>itemNum = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };//Item number from 0 to 8
    vector<int>Sold(DefaultNSold.size());//receive number sold for each item.
    vector<float>totalValue(DefaultNSold.size());
    getnumSold(Sold);//passing vector Sold to function getnumSold(). Return of #sold of each item
    DollarSales(Sold, totalValue); // pass #sold in vector Sold, and return total sold value of each item.
    displayProd(Sold, totalValue);//Show all the tittles of the items
    sortSales(totalValue, itemNum);// pass total sold value of each item to sort highest to lowest total $ of items.
                                    // also return the order of the items from highest to lowest for sorting.
    displaySales(Sold, totalValue, itemNum);// Display from highest to lowest the total sales of items.
    return 0;                    
}

void getnumSold(vector<int>& numSold)// get and return vector numSold to vector Sold
{
    char select;
    count << " Enter y to use default numbers, any other character";
    count << "for entering 6 new numbers: "; cin >> select;
    if ((select == 'y') || (select == 'Y'))
    {
        int row=1;
        count << " In getnumSold, You chose to use default = {";
        for (row = 1; row < DefaultNSold.size(); row++)
        {
            numSold[row - 1] = DefaultNSold[row - 1];
            count << numSold[row - 1] << " ";
        }
        numSold[row - 1] = DefaultNSold[row - 1];
        count << numSold[row - 1] << "}\n\n";
    }
    else
    {
        count << " You chose to enter 9 new sales number.\n\n";
        count << "Enter number sold for the following\n\n";
        for (int row = 1; row <= DefaultNSold.size(); row++)
        {
            count << "   " << left << setw(35) << Prod[Row-1] << left <<
                setw(15) << Desc[row-1] << "$" << Price[row-1] << " is:   ";
            cin >> numSold[row-1];
        }
    }
}
void displayProd(vector<int>& Sold, vector<float>totVal)// display the table of selections and price.
{
    count << " In displayProd\n\n";
    count << left << setw(35) << "     Product" << setw(15) << "Decription" << setw(10) << "Part num" <<
        setw(15) << "   Price" << setw(10) << "sold" << setw(17) << "total" << "\n\n";
    for (int line = 0; line < Row; line++)
    {
        count << "  " << left << setw(35) << Prod[line] << left << setw(15) <<
            Desc[line] << setw(10) << pnAr[line] << "$" << Price[line] <<
            right << setw(10) << Sold[line] << setw(7) <<"$" << left <<  totVal[line] << "\n\n";
    }
}
void DollarSales(vector<int>&Sold, vector<float>&totalValue)// receive vector Sold and vector itemNum.
{                                                   // return to vector Sold.
    int size = Sold.size();
    for (int element = 0; element < size; element++)
    {
        totalValue[element] = Price[element] * Sold[element];
        //count << totalValue[element] << "\n\n";
    }
}
void sortSales(vector <float>Ar, vector<int>& itemN)// receive vector Sold and vector itemNum.
//function return vector itemN that contain the order of the items sorted from lowest
// total sales to highest.
{
    int size = Ar.size();// find the size of the vector. 
    int startScan = 0, index, temp2;
    float temp1;
    do
    {
        index = startScan + 1; // startScan is the first element number, index is the following number.
        while (index < size)
        {
            if (Ar[startScan] < Ar[index])//comparing the lowest number element starting with AR[0] to the rest
            {                    // one by oneswitch with them if it is higher than the other elements.
                temp1 = Ar[startScan];    temp2 = itemN[startScan];
                Ar[startScan] = Ar[index];    itemN[startScan] = itemN[index];
                Ar[index] = temp1; itemN[index] = temp2;
            }
            index = index + 1;// to the next lower element to compare,  AR[1]->AR[2]-> AR[3]...
        }
        startScan = startScan + 1;
    } while (startScan < (size - 1));
}
void displaySales(vector<int>Sold, vector<float>totalValue, vector<int> itemN)
{
    count << "\n\n\n\n After sorting with the highest dollar amount first \n\n";
    count << left << setw(35) << "     Product" << setw(15) << "Decription" << setw(10) << "Part num" <<
    setw(15) << "   Price" << setw(10) << "sold" << setw(17) << "total" << "\n\n";
    int Row = Sold.size();
    for (int line = 0; line < Row; line++)
    {
        count << "  " << left << setw(35) << Prod[itemN[line]] << left << setw(15) <<
            Desc[itemN[line]] << setw(10) << pnAr[itemN[line]] << "$" << Price[itemN[line]] <<
            right << setw(10) << Sold[itemN[line]] << setw(7) << "$" << left << totalValue[itemN[line]] << "\n\n";
    }
}

I am done with Chapter 8, this is a lot more difficult than any problem in the book on chapter 8. I use a lot of vectors instead of arrays so to make it easier to expand the number of items as needed. Only the old ones are in array that I did not convert to vectors.

I only put the text display arrays in global section, those are not going to be changed. All the vectors that the program work on are parameters passing to function from main. They stay local as much as possible. The program is calling function to do everything, the main is only about 12 lines.
 
Last edited:
  • #76
jedishrfu said:
The old programming mantra still holds:
_ I can make it fast
- I can make it cheap
- I can make it reliable

pick any two and let me know.

Of course, bosses today will pick two and then ding you on the one they didn't choose.

Never truer words spoken...
 
  • #77
For memory efficiency:

C++:
struct boolmap {
    char x:1;
    char y:1;
    char z:1;
};
 
  • #78
Dr Transport said:
Never truer words spoken...
I assume make it fast meaning the speed, not deliver the program fast. One thing I always told my people, do NOT rush, don't wait until the last minute to do the job. Take the time to do it right, think it out first, don't rush in.

I am proud to say in my career, hardware always ahead of schedule way before the mechanical and software group. I hate the marketing schedule, they think if they put in unrealistic schedule, they can pressure people to work faster. Nothing is more time wasting than doing it wrong, then having to bandage it back. That's wasting money, wasting time.

I monitor my people, make sure they take the time to do it right, quality control right from the beginning. Might have a slow start, but we always finish ahead.

Back to the 3 options: make it fast( as running speed), I pick 1 and 3 any time of the day. I talked about this many times here already how frustrating that the newer stuffs are getting slower and stupider. Too many fancy feature in the name of nobody left behind, that even the stupidest people can stumble through. I want things to respond fast. I want things that work. Nothing is more frustrating than my 2 year old car spent over 5 weeks in the shop the first 8 months ALL software problems. All the intermittents and lockups.

Nothing costs more money than a bad design and resort to bandage it up, then bandage the bandage.
 
  • #79
One thing that is way off the subject but is of utmost important for reliability...Programming FPGA. Software people might look at VHDL or AHDL( Altera's own language) and think it's easy as it looks like any computer language......Don't even think about it. The language is almost the same, but the effect is totally different. The difference is in software, everything is working is sequence, one step at a time. FPGA signal are working in PARALLEL. You might think you program one step at a time, but all steps are working at the same time in FPGA. If software people want to move into FPGA programming, make sure to take a basic digital class first, learn about timing and all before they even touch this. So many mistake are made because people don't understand. I wrote FPGA programming because I understand digital hardware. I program as if it is a circuit, not a program. I had to troubleshoot problems with FPGAs written by someone else. Any language is only a tool, it's only a means to an end. Have to know to big picture.

Funny in my gym, one guy was the top dog manager in Lockheed at the time, we were talking about about circuit design and topic landed on FPGA, when I was telling him all the trouble I had to go through troubleshooting the glitches from FPGAs, he offered me a job on the spot! I was laughing! I retired already, I have no intention of working again.
 
  • #80
I have a question on initialize pointer. The books said it's illegal to do this:
C++:
float myFloat;
int *pint = &myFloat;

I understand myFloat is a float, not an int. But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
 
  • #81
yungman said:
I have a question on initialize pointer. The books said it's illegal to do this:
C++:
float myFloat;
int *pint = &myFloat;

I understand myFloat is a float, not an int. But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
What do you think is the type of &myFloat?
 
  • #82
Jarvis323 said:
You need to slow down and learn what the code you are writing actually means, not just what you expect it to do.
+1
 
  • #83
yungman said:
C++:
float myFloat;
int *pint = &myFloat;
I understand myFloat is a float, But the starting address of the variable myFloat is an int. Why can't you initialize int *pint to the address of myFloat?
It's because there generally aren't just plain pointers -- they are almost always pointers to some particular type. In your example, myFloat is a pointer to type float. pint is a pointer to an int. You can't do what you're trying to do without some casts, and even then, you might not get what you expect.
Here's an updated version of your example.
C++:
float myFloat = 3.75F;
int * pInt = (int *)(&myFloat);
int val = *pInt;
Note that I'm using the old-style casts.
In this code, val gets set to 0x40700000, or decimal 1081081856. These are the integer representations of the float 3.75.
 
  • Like
Likes yungman
  • #84
Jarvis323 said:
What do you think is the type of &myFloat?
Integer!, it's the address of the first byte of the variable myFloat.

It points to the first byte of the variable, who cares whether it's a float or int or anything.
 
Last edited:
  • #85
yungman said:
Integer!, it's the address of the first byte of the variable myFloat.

It points to the first byte of the variable, who cares whether it's a float or int or anything.
There's your problem. You don't know what the type is.
 
  • #86
Jarvis323 said:
There's your problem. You don't know what the type is.
Is int *pint declare the ADDRESS?

Is &myfloat giving you the address of the first byte of the variable of myfloat?

It's the address, who cares about whether the content of myfloat is a float or int. It's the address.
 
  • #87
yungman said:
Is int *pint declare the ADDRESS?
No. It's a variable that can be used to store an address to an int. Its type is (int*).
yungman said:
Is &myfloat giving you the address of the first byte of the variable of myfloat?
It's giving you a value of a particular type (int*), that holds the first byte of the variable myfloat.

In C and C++ you have formal types with precise definitions, and the compiler does type checking to make sure the types you are using match up.

yungman said:
It's the address, who cares about whether the content of myfloat is a float or int. It's the address.
See Mark's post to see why it's not the same thing, and doesn't give the same results whether it's a float or int.
 
Last edited:
  • Like
Likes yungman
  • #88
Jarvis323 said:
In C and C++ you have formal types with precise definitions, and the compiler does type checking to make sure the types you are using match up.
I am ok if you said you are NOT allow to do this, I can obey that. BUT if the book said int *pint declares an address, and the address of a float is an integer, there is a problem. That's why I post the question here.

BTW, do NOT ever take what the books said is the truth. I challenged the most famous book on Phase Lock Loop and the author offered me to send me the manuscript of the latest version. They are only human.

I just read the Gaddis book and put it in the notes with page number. You can check if I am right, this is my understanding. It is on the notes of Chapter 9 page 496.
 

Attachments

  • #89
yungman said:
I am ok if you said you are NOT allow to do this, I can observe that. BUT if the book said int *pint declares an address, and the address of a float is an integer, there is a problem.

There is no type that is called (address), or (integer) in the C++ type system. The book is not wrong. You just don't understand what a type is. What you are reading in the book is an english description of what it is, not what it's type is.
 
  • Like
Likes yungman
  • #90
Jarvis323 said:
There is no type that is called (address). And integer isn't a type in the C++ type system. The book is not wrong. You just don't understand what a type is.
Yes, it said int *pint define as address of pointer pint. int *pint initiates a pointer of address.
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 6 ·
Replies
6
Views
2K
Replies
1
Views
2K
Replies
3
Views
1K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 75 ·
3
Replies
75
Views
6K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 6 ·
Replies
6
Views
4K