Writing a loop on menu bar

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
ONEEYEMAN
Part Of The Furniture
Part Of The Furniture
Posts: 7458
Joined: Sat Apr 16, 2005 7:22 am
Location: USA, Ukraine

Writing a loop on menu bar

Post by ONEEYEMAN »

Hi,
Consider following code:

Code: Select all

for( size_t I = mbar->GetMenuCount(); I >= 0; --i )
{
    delete mbar->Remove( i );
》
This code will fail since size_t will become MAX_INT.

So how to properly write this? Can I just use int and don't have warning?

Thank you.
AmadeusK525
Experienced Solver
Experienced Solver
Posts: 60
Joined: Wed Aug 19, 2020 12:04 am

Re: Writing a loop on menu bar

Post by AmadeusK525 »

Yes, that would be it. Since you don't stop after 'i' gets to 0, there won't be any errors in the code if you use an int. I've run into this problem multiple times: When writing a 'for' loop that goes down instead of up, using size_t is generally a bad idea
ONEEYEMAN
Part Of The Furniture
Part Of The Furniture
Posts: 7458
Joined: Sat Apr 16, 2005 7:22 am
Location: USA, Ukraine

Re: Writing a loop on menu bar

Post by ONEEYEMAN »

Hi,
Yes, except that it might give me a warning during compilation, which I'd rather avoid.
And of course the "GetMenuCount() returns "size_t" so there is no workaround for that.

Thank you.
Kvaz1r
Super wx Problem Solver
Super wx Problem Solver
Posts: 357
Joined: Tue Jun 07, 2016 1:07 pm

Re: Writing a loop on menu bar

Post by Kvaz1r »

Just use static_cast and there won't be warnings.
Manolo
Can't get richer than this
Can't get richer than this
Posts: 827
Joined: Mon Apr 30, 2012 11:07 pm

Re: Writing a loop on menu bar

Post by Manolo »

If you use static cast, you may hide some issue. Dangerous.
If you use 'int' instead of 'size_t' you may get warnings.
What I do in a down-loop where i=0 is valid, is add a break condition:

Code: Select all

for( size_t i = mbar->GetMenuCount(); i >= 0; --i )
{
    delete mbar->Remove( i );
    if (i==0)
        break;
》
Or replace the for loop with a while one.
Post Reply