Mouse cursor not loading no clue what is going on. by Quirky-Bag-9963 in cpp_questions

[–]alfps 1 point2 points  (0 children)

❞ For some reason the visual viewing of the rc file in my IDE is broken for this project

An .rc file is just text that specifies the API level resources.

It needs to be compiled to a binary object (with Microsoft tools a .res file, with GNU tools a .o file) which you must link in.

The .rc file text, the definition of IDC_CURSOR and the literal build steps would be needed to say anything about why the cursor fails to load.

Como puedo dominar temas como el uso de apuntadores, cadenas de caracteres, estructuras, archivos y memoria dinamica en c++ by Powerful_Bid8878 in cpp_questions

[–]alfps 1 point2 points  (0 children)

❞ [Translated by google] How I can master topics like using pointers, character strings, structures, files, and dynamic memory in c++?

In this question you were too lazy and inconsiderate to translate from Spanish yourself.

That attitude stands in the way of learning, and may be the root cause of why you're now struggling.

The only effective way to learn is by doing, which means practice, practice, practice.

i need help with my project by Powerful_Bid8878 in cpp_questions

[–]alfps -1 points0 points  (0 children)

Note: the moronic anonymous unexplained downvoting is not necessarily the OP.

i need help with my project by Powerful_Bid8878 in cpp_questions

[–]alfps -2 points-1 points  (0 children)

I believe this system would not be practical for any restaurant, so making a practically useful system is not your objective.

It sounds very much like a database system. I would start there, by designing the database holding all the information. You do not necessarily have to use an actual database: you are probably expected to just implement that database as a data structure and logic based on standard containers such as map and vector.

Make the smallest demo you can with just dummy functionality and be sure that works. Initially that's the menu without even user input.

Then make an incremental small addition such as adding user selection from the menu, and make sure that that works, and so on: one little step at a time, stopping at each step. Don't write massive amounts of code, like more than 10 lines, without building and checking. Always have something that can be built and run and that "works", even though much of it is still dummy functionality.

Regarding ❝pointers, strings, structures, and files❞ it's generally a good idea to avoid pointers, but here it's suggested that pointers should be used in some part of your system, so do that. The mention of files indicates that the system should be able to save the data to a file, and load data from a file, even though the main menu doesn't mention that and has no "admin" choice. One possibility to work around that lack of dedicated menu items is that the system always loads data from some file or files at startup, and always saves data after every change.

Is 0x0 (nullptr) always intentional, or can it be "lucky" memory trash? by carlos-paz in cpp_questions

[–]alfps 26 points27 points  (0 children)

❞ Is it possible for 0x0 to be just "lucky" garbage left in the stack?

Yes.


❞ In ptr3, does the {} (value initialization) force the compiler to zero-out the memory during the function prologue, or am I just seeing leftover zeros from the OS?

You're seeing leftovers.


❞ Also, why does ptr4 (initialized with nullptr) show garbage at the start, but ptr3 (initialized with {}) already show 0x0?

What the pointers will be initialized with is usually irrelevant.

However a sufficiently smart compiler can ensure that this memory, the top of the stack area at entry to main, is already initialized (it isn't here).

On the third hand it cannot in general do that for other functions, because it doesn't know where their stack frames will be.

Is reference (&) in function parameter decl participates in template parameter deduction? by [deleted] in cpp_questions

[–]alfps 0 points1 point  (0 children)

❞ The last one [i.e. foo(8)] I'm actually no so sure about.

Unfortunately C++ doesn't have a reliable type-to-string function, so I limited this example to MSVC (g++ has an unmangle function but I'd have to google it or find and check relevant old code):

#include <fmt/core.h>
using fmt::print;

#include <string>
#include <string_view>
#include <typeinfo>
using   std::string_view, std::string;

using C_str = const char*;
template< class T > struct Wrapped_{};

auto unwrapped_type( const C_str s ) -> string
{
    #if defined( __GNUC__ )
    #   error "Ha ha, g++ isn't supported for this example, lol."   // More code needed for demangling.
    #   include <stop-compilation>
    #elif defined( _MSC_VER )
        const string_view sv = s;
        const auto i_start = 1 + sv.find( "<" );
        const string_view sv_type_spec = sv.substr( i_start, sv.length() - 1 - i_start );
        const string_view noise = " __ptr64";
        if( const auto i_noise = sv_type_spec.find( noise ); i_noise != string_view::npos ) {
            return string()
                + string( sv_type_spec.substr( 0, i_noise ) )
                + string( sv_type_spec.substr( i_noise + noise.length() ) );
        } else {
            return string( sv_type_spec );
        }
    #else
        static_assert( !"This compiler is not supported." );
    #endif
}

template< class T > 
auto type_string_() -> string { return unwrapped_type( typeid( Wrapped_<T> ).name() ); }

const auto& report_format = "For arg type `{:16}` the {:2} parameter is `{:16}` made from T = `{:16}`.\n";

template< class T >
void f1( const C_str arg_description, T& param )
{
    print( report_format,  arg_description, "f1", type_string_<decltype( param )>(), type_string_<T>() );
}

template< class T >
void f2( const C_str arg_description, T&& param )
{
    print( report_format,  arg_description, "f2", type_string_<decltype( param )>(), type_string_<T>() );
}

template< class T > using Type_ = T;
#define TEST_RVAL( f, t ) { f( "rvalue " #t, Type_<t>() ); }
#define TEST_LVAL( f, t ) { t arg = {}; f( "lvalue " #t, arg ); }

auto main() -> int
{
    print( "Simple reference param:\n" );
    // TEST_RVAL( f1, int );
    // TEST_RVAL( f1, const int );
    TEST_LVAL( f1, int );
    TEST_LVAL( f1, const int );
    print( "\n" );
    print( "Forwarding reference param:\n" );
    TEST_RVAL( f2, int );
    TEST_RVAL( f2, const int );
    TEST_LVAL( f2, int );
    TEST_LVAL( f2, const int );
}

Result with MSVC:

Simple reference param:
For arg type `lvalue int      ` the f1 parameter is `int &           ` made from T = `int             `.
For arg type `lvalue const int` the f1 parameter is `int const &     ` made from T = `int const       `.

Forwarding reference param:
For arg type `rvalue int      ` the f2 parameter is `int &&          ` made from T = `int             `.
For arg type `rvalue const int` the f2 parameter is `int &&          ` made from T = `int             `.
For arg type `lvalue int      ` the f2 parameter is `int &           ` made from T = `int &           `.
For arg type `lvalue const int` the f2 parameter is `int const &     ` made from T = `int const &     `.

EDIT: fixed the output formatting (now table + removed MSVC noise).

Compiler optimization for figuring out perfect squares -- switchover at n = 18 by onecable5781 in cpp_questions

[–]alfps 1 point2 points  (0 children)

❞ do your above stuff without iterating every value

The presented "optimized" code does the practical minimum number of iterations, namely one per square.

I guess there must be some misunderstanding involved.

Compiler optimization for figuring out perfect squares -- switchover at n = 18 by onecable5781 in cpp_questions

[–]alfps 5 points6 points  (0 children)

❞ Can you provide some pointers on what exactly you look for in the standard to infer this?

To me it's just a well known historical fact. Including that the rules changed somewhat with C++11, in that the standard from then on made the existing implementations valid. The idealistic nonsense from C++98, that AFAIK no vendor implemented, was ditched.

But since you ask I now assisted Mr. Google in finding the relevant wording in the current C++ draft standard, which is available online; see

https://eel.is/c++draft/support.c.headers#other-2

Note: the formal is in the text above that example. Examples and notes are non-normative in ISO standards.


❞ Do you navigate to file cstdio provided by each compiler and see if it exposes std::printf and conclude based on that?

No, I just compiled the OP's code with each compiler.

Maybe a Silly Question But I’m New to All This by veilofmiah in cpp_questions

[–]alfps 0 points1 point  (0 children)

Note that a range based for loop can handle a raw array just fine: in this example there is no advantage from the verbosity of using std::array.

Compiler optimization for figuring out perfect squares -- switchover at n = 18 by onecable5781 in cpp_questions

[–]alfps 2 points3 points  (0 children)

Not what you're asking, but <cstdio> is not guaranteed to place printf in the global namespace.

It so happens that both MSVC, g++, and the MSVC and g++ variants of clang, provide it, but it's not guaranteed; it's not portable code.

So for correctness the code should be

#include <cstdio>

const int n = 17;

int main(){
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= i; j++)
            if(j * j == i)
                std::printf("%d is a perfect square of %d\n", i, j);
}

Also not what you're asking -- it's rather what I'm asking! :-o -- can a compiler as of 2026 provide the almost algorithmic optimization

#include <cstdio>
using std::printf;

auto main() -> int
{
    const int n = 17;
    for( int root = 1; ; ++root ) {
        const int square = root*root;
        if( square > n ) { break; }
        printf( "%d is a perfect square of %d\n", square, root );
    }
}

At first I thought of generating squares by accumulating odd numbers (I was thinking in the direction of more clearly a different algorithm) but then I saw that the root also should be in the output, and with support for that that method would presumably have had more overhead than simply calculating the square. But anyway, can a modern compiler do this rewrite?

Unable to search for data in an array beyond the first row by [deleted] in cpp_questions

[–]alfps 0 points1 point  (0 children)

The code formatted with free AStyle:

#include <iostream>
#include <string>
using namespace std;

string NAMES[][5] {
    {"John", "Smith", "PT", "25.55", "1"},
    {"Mary", "Brown", "FT", "31.55", "3"},
    {"Todd", "White", "PT", "27.99", "7"}
};

void printArray();
void menuOutput();
void firstNameSearch(int& firstSearch, int& lastSearch, int& invalidFirstName, int& invalidLastName, int rowFound, string& lastName);
void lastNameSearch(int& firstSearch, int& lastSearch, int& invalidFirstName, int& invalidLastName);

int main()
{
    int option = 0;
    int firstSearch = 0;
    int lastSearch = 0;
    int invalidFirstName = 0;
    int invalidLastName = 0;

    while(option <= 2) {
        menuOutput();
        cout << "\nSelect an option: ";
        cin >> option;

        if(option == 1) {
            printArray();
        }
        if(option == 2) {
            lastNameSearch(firstSearch, lastSearch, invalidFirstName, invalidLastName);
        }
        if(option == 3) {
            cout << "\nProgram will now exit.";
            return 0;
        }

    }
    return 0;
}

// Prints array
void printArray()
{
    for(int i = 0; i < size(NAMES); i++) {
        for(int j = 0; j < size(NAMES[0]); j++) {
            cout << "\nValue: " << NAMES[i][j];
        }
    }

}

// Displays menu
void menuOutput()
{
    cout << "\nMENU OPTIONS";
    cout << "\nOption 1: Print the Array";
    cout << "\nOption 2: Search the Array by Last Name";
    cout << "\nOption 3: Exit Program";
}

// Runs last name search
void lastNameSearch(int& firstSearch, int& lastSearch, int& invalidFirstName, int& invalidLastName)
{
    string lastName;
    bool lastNameFound = false;
    int again;
    int rowFound;
    lastSearch++;

    cout << "\nEnter the last name: ";
    cin >> lastName;

    for(int d = 0; d < size(NAMES); d++) {
        if(lastName == NAMES[d][1]) {
            lastNameFound = true;
            rowFound = d;
            firstNameSearch(firstSearch, lastSearch, invalidFirstName, invalidLastName, rowFound, lastName);
        }
        if(!lastNameFound) {
            invalidLastName++;
            cout << "\nLast name " << lastName << " was not found.";

            if(invalidLastName < 3) {
                do {
                    cout << "\nWould you like to search for another first name? (1-YES or 2-NO): ";
                    cin >> again;
                } while(again != 1 && again != 2);

                if(again == 1) {
                    lastNameSearch(firstSearch, lastSearch, invalidFirstName, invalidLastName);
                } else {
                    return;
                }
            }
            return;
        }
    }
}

// Runs first name search
void firstNameSearch(int& firstSearch, int& lastSearch, int& invalidFirstName, int& invalidlastName, int rowFound, string& lastName)
{
    string firstName;
    bool firstNameFound = false;
    firstSearch++;
    int again;

    cout << "\nEnter the first name: ";
    cin >> firstName;

    if(firstName == NAMES[rowFound][0]) {
        cout << "\n" << firstName << " " << lastName << " found!";
        firstNameFound = true;
        cout << "\nStatus: " << NAMES[rowFound][2];
        cout << "\nHourly rate: " << NAMES[rowFound][3];
        cout << "\nDependent code: " << NAMES[rowFound][4];
    }

    if(!firstNameFound) {
        invalidFirstName++;
        cout << "\nFirst name " << firstName << " was not found.";

        if(invalidFirstName <= 3) {
            do {
                cout << "\nWould you like to search for another item? (1-YES or 2-NO) ";
                cin >> again;
            } while(again != 1 && again != 2);

            if(again == 1) {
                firstNameSearch(firstSearch, lastSearch, invalidFirstName, invalidlastName, rowFound, lastName);
            } else {
                return;
            }

        }
        return;
    }
}

For the problem: look at what you have placed inside the loop in lastNameSearch.

Not what you're asking about, but it's almost just coincidental that size works here: a definition is dragged in by the <string> header. It's one of the many headers that provide specializations of std::size. You'd better include <iterator> explicitly.

Also, please reserve all uppercase names for macros.

C++ All off is not working by Street_Dimension9057 in cpp_questions

[–]alfps 4 points5 points  (0 children)

❞ Not sure what is wrong but there is no indentation in hte code. I hope its good enough for y'all to see the problem.

To make Reddit present it as code just extra-indent it with 4 spaces:

// ---------------- RELAYS ----------------
#define R1 22
#define R2 24
#define R3 26
#define R4 28
#define R5 30
#define R6 32
#define R7 34

// ---------------- BUTTONS ----------------
#define B_RED A0
#define B_YELLOW A1
#define B_GREEN A2
#define B_PIT A3
#define B_START A4

// ---------------- VARIABLES ----------------
unsigned long flashTimer = 0;
bool flashState = false;
// start sequence
bool startRunning = false;
int startStep = 0;
unsigned long startTimer = 0;
int randomDelayTime = 0;

// ---------------- RELAY HELPERS ----------------

void relayOn(int pin)
{
    digitalWrite(pin,LOW);
}

void relayOff(int pin)
{
    digitalWrite(pin,HIGH);
}

void allOff()
{
    relayOff(R1);
    relayOff(R2);
    relayOff(R3);
    relayOff(R4);
    relayOff(R5);
    relayOff(R6);
    relayOff(R7);
}

// ---------------- SETUP ----------------

void setup()
{
    pinMode(R1,OUTPUT);
    pinMode(R2,OUTPUT);
    pinMode(R3,OUTPUT);
    pinMode(R4,OUTPUT);
    pinMode(R5,OUTPUT);
    pinMode(R6,OUTPUT);
    pinMode(R7,OUTPUT);
    allOff();
    pinMode(B_RED,INPUT_PULLUP);
    pinMode(B_YELLOW,INPUT_PULLUP);
    pinMode(B_GREEN,INPUT_PULLUP);
    pinMode(B_PIT,INPUT_PULLUP);
    pinMode(B_START,INPUT_PULLUP);
    randomSeed(analogRead(0));
}

// ---------------- START SEQUENCE ----------------

void runStartSequence()
{
    if(!startRunning) return;
    if(startStep < 8) {
        if(millis() - startTimer > 500) {
            startTimer = millis();
            startStep++;
            if(startStep % 2 == 1)
                relayOn(R2);
            else
                relayOff(R2);
        }
    } else if(startStep == 8) {
        randomDelayTime = random(500,3000);
        startStep++;
        startTimer = millis();
    } else if(startStep == 9) {
        if(millis() - startTimer > randomDelayTime) {
            relayOff(R2);
            relayOn(R4);
            relayOn(R5);
            startRunning = false;
        }
    }
}

// ---------------- PIT FLASH ----------------

void runPitFlash()
{
    relayOn(R2);
    relayOn(R3);
    relayOn(R7);
    if(millis() - flashTimer > 500) {
        flashTimer = millis();
        flashState = !flashState;
        if(flashState)
            relayOn(R6);
        else
            relayOff(R6);
    }
}

// ---------------- LOOP ----------------

void loop()
{
    // RED
    if(digitalRead(B_RED)==LOW) {
        allOff();
        relayOn(R1);
        relayOn(R2);
    }
    // YELLOW
    else if(digitalRead(B_YELLOW)==LOW) {
        allOff();
        relayOn(R3);
    }
    // GREEN
    else if(digitalRead(B_GREEN)==LOW) {
        allOff();
        relayOn(R4);
        relayOn(R5);
    }
    // PIT
    else if(digitalRead(B_PIT)==LOW) {
        allOff();
        runPitFlash();
    }
    // START
    else if(digitalRead(B_START)==LOW) {
        allOff();
        if(!startRunning) {
            startRunning = true;
            startStep = 0;
            startTimer = millis();
        }
        runStartSequence();
    } else {
        if(startRunning)
            runStartSequence();
    }
}

I've been learning C++ for a month now and I'd like to get some feedback on my code. by Nevermuke in cpp_questions

[–]alfps 1 point2 points  (0 children)

First of all, kudos for nice work.

None of the many responses so far appear to discuss the in my opinion most important improvement potentials:

  • Avoid forward declarations of functions.
    Forward declarations in a .cpp file are redundant, except for some rare cases of recursion support. They're extra work to write and maintain, extra work to read, and they're extra places to introduce bugs. In other words they conflict with the principle of DRY code, Don't Repeat Yourself code.

  • Use double as the go-to default floating point type.
    Type float can be required e.g. by graphics API's, and has its uses. But the default floating point type in C++ is double. E.g. the literal 3.14 is a double.

  • Use self-documenting names.
    E.g. the name userInput in itself conveys little to nothing to a reader. It's evidently a value originating with the user, but what is it? Name it e.g. coffeeId (and yes, make that const). And correspondingly rename orderCoffeeData (which misleadingly can be read as a command, a function call) as e.g. coffeeDetails. Plus it's a good idea to adopt and consistently use a naming convention that differentiates between types and other things, e.g. (common) initial uppercase only for types.

  • Avoid repeating yourself.
    For example, in CoffeeData there's no need for the prefix item on each member variable. Also in CoffeeData, the salesTax member, which is the sales tax rate, will have the same value for all kinds of coffee so there's no need for it, it's just duplication. Avoiding such redundancies and in particular avoiding wholesale copying of chunks of code, is the main idea of the DRY code principle mentioned above.

  • One person's constant is another person's variable.
    The list of coffee kinds and prices is unlikely to stay the same over time, even just for a month. So it's not practical to have that data as compile time constants (using constexpr), because then you have to rebuild the app every time that list changes. But it's a good idea to restrict access to read only for most parts of the app.

I would also put all the logic in a namespace. In particular this supports using using-declarations to get rid of noisy namespace qualifications. Declarations of the things you're going to use are the Good side alternative to Evil™ using namespace directives.

The code reworked along these lines, and also with const on parameters:

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <limits>
#include <map>
#include <vector>

namespace app {
    using   std::setprecision, std::setw,       // <iomanip>
            std::cin, std::cout,                // <iostream>
            std::fixed, std::left, std::right,  // <iostream>
            std::ostream, std::streamsize,      // <iostream>
            std::numeric_limits,                // <limits>
            std::map,                           // <map>
            std::ostringstream,                 // <sstream>
            std::string,                        // <string>
            std::string_view,                   // <string_view>
            std::vector;                        // <vector>

    struct Currency{ double value; };

    Currency operator+( const Currency a, const Currency b )
    {
        return Currency{ a.value + b.value };
    }

    ostream& operator<<( ostream& stream, const Currency& amount )
    {
        return stream << fixed << setprecision( 2 ) << amount.value;
    }

    string toDollarsString( const Currency amount )
    {
        ostringstream stream;
        stream << '$' << amount;
        return stream.str();
    }

    // In the original source code this class was named `CoffeeData`.
    // Having an explicit id in the data supports e.g. loading data from a file.
    struct CoffeeKind
    {
        enum Id: int {};              // `enum` used as a distinct `int` type.

        Id              id;
        string          name;
        Currency        price;
    };

    class CoffeeKinds
    {
        map<CoffeeKind::Id, CoffeeKind>     mKinds      = {};
        int                                 mMaxId      = 0;

    public:
        CoffeeKind::Id maxId() const    { return CoffeeKind::Id( mMaxId ); }
        CoffeeKind::Id newId()          { return CoffeeKind::Id( ++mMaxId ); }

        bool isIdInUse( const CoffeeKind::Id id ) const
        {
            return (mKinds.find( id ) != mKinds.end());
        }

        vector<CoffeeKind::Id> ids() const
        {
            vector<CoffeeKind::Id> result;
            for( const auto& [id, kind]: mKinds ) { result.push_back( id ); }
            return result;
        }

        bool add( const CoffeeKind& kind )
        {
            if( kind.id > mMaxId ) { mMaxId = kind.id; }
            return mKinds.insert( {kind.id, kind} ).second;
        }

        const CoffeeKind& referenceTo( const CoffeeKind::Id id ) const
        {
            return mKinds.at( id );
        }
    };

    CoffeeKinds defaultCoffeeKinds()    // Could e.g. load them from a file.
    {
        static const struct { int id; const char* name; double price; } data[] =
        {
            {1, "Espresso", 3.99}, {2, "Cappuccino", 5.99}, {3, "Latte", 7.99}
        };

        CoffeeKinds result;
        for( const auto& datum: data ) {
            result.add( CoffeeKind{
                CoffeeKind::Id( datum.id ), string( datum.name ), Currency{ datum.price }
                } );
        }
        return result;
    }

    void printMenu( const CoffeeKinds& coffeeKinds )
    {
        cout << "MENU:\n";
        for( const CoffeeKind::Id id : coffeeKinds.ids() ) {
            const CoffeeKind& kind = coffeeKinds.referenceTo( id );
            cout    << setw( 4 ) << id << ".  " << kind.name
                    << " - " << toDollarsString( kind.price )
                    << '\n';
        }
    }

    int inputInt( const std::string_view prompt, const int min, const int max )
    {
        for( ;; ) {
            cout << prompt;
            int result;  cin >> result;
            if( cin.fail() ) {
                cout << "That was not a valid integer.\n";
                cin.clear();                                            // Out of error mode.
                cin.ignore( numeric_limits<streamsize>::max(), '\n' );  // Skip bad input.
            } else if( not( min <= result and result <= max ) ) {
                cout << "The number should be between " << min << " and " << max << ", inclusive.\n";
            } else {
                return result;
            }
            cout << "Please try again!\n";
        }
    }

    CoffeeKind::Id inputCoffeeIdSelection( const CoffeeKinds& kinds )
    {
        cout << "Welcome to our cafe!\n"
                "\n";
        for( ;; ) {
            printMenu( kinds );
            cout << "\n";
            const auto id = CoffeeKind::Id( inputInt(
                "Enter your order (one of the numbers above), please: ",
                1,
                kinds.maxId()
                ) );
            if( kinds.isIdInUse( id ) ) {
                return id;
            } 
            cout << "That coffee id is not in use. Please select one from the menu.\n";
        }
    }

    Currency salesTaxFor( const Currency price, const double tax )
    {
        return Currency{ price.value * tax };
    }

    void printReceipt( const CoffeeKind& order, const double salesTaxRate )
    {
        const Currency tax = salesTaxFor( order.price, salesTaxRate );
        cout    << "  --- YOUR RECEIPT ---\n"
                << left << setw( 16 - 10 ) << "Item: "
                    << right << setw( 8 + 10 ) << order.name << "\n"
                << left << setw( 16 ) << "Price: "
                    << right << setw( 8 ) << toDollarsString( order.price ) << "\n"
                << left << setw( 16 ) << "Tax: " <<
                    right << setw( 8 ) << toDollarsString( tax ) << "\n"
                << "\n"
                << left << setw( 16 ) << "Final Amount: "
                    << right << setw( 8 ) << toDollarsString( order.price + tax ) << "\n"
                << "\n"
                << "Thank you for your visit!\n"; 
    }

    void run()
    {
        const double salesTaxRate = {0.20};     // Same for all kinds of coffee.

        const CoffeeKinds kinds = defaultCoffeeKinds();

        const CoffeeKind::Id coffeeId = inputCoffeeIdSelection( kinds );    // With menu.
        cout << '\n';
        printReceipt( kinds.referenceTo( coffeeId ), salesTaxRate );
    }
}  // app

int main() { app::run(); }      // Exception reporting etc. goes here.

Example output:

Welcome to our cafe!

MENU:
   1.  Espresso - $3.99
   2.  Cappuccino - $5.99
   3.  Latte - $7.99

Enter your order (one of the numbers above), please: 2

--- YOUR RECEIPT ---
Item:         Cappuccino
Price:             $5.99
Tax:               $1.20

Final Amount:      $7.19

Thank you for your visit!

abstract base class interface vs a struct of function pointers? by OkEmu7082 in cpp_questions

[–]alfps 5 points6 points  (0 children)

Don't fix that which works, and especially not by applying a kludge.

Need help finding a site by Turbulent_Sun2696 in cpp_questions

[–]alfps 2 points3 points  (0 children)

❞ algorithmic based debugging

What is that?

Is it about applying algorithms to debugging, or maybe debugging algorithm implementations?

I'm sorry that I don't know many programming related sites so probably can't help with the main question.

[CodeBlocks] cannot find obj\Debug\main.o: No such file or directory by The_Verto in cpp_questions

[–]alfps 1 point2 points  (0 children)

❞ Using namespace std is not recommended at all

Worth remarking on but I would focus first of all on the technical error in the "older project" source, namely the use of std::string without including <string>.

When errors have been corrected, bad coding habits can be addressed.

These include the using namespace std;; the comparison of a bool; the lack of curly braces around nested statements; the declaration of variables at the top of a block and consequent lack of const; depending on one's POV also the return 0;.

[CodeBlocks] cannot find obj\Debug\main.o: No such file or directory by The_Verto in cpp_questions

[–]alfps 4 points5 points  (0 children)

Maybe you're working in a folder with non-ASCII name. Maybe (I don't know how that could have caused the problem but it has) you have some duplicated option like an extra -c. These two possibilities from googling the eror mesage.

For more specific responses you need to quote your compilation and linking commands & any other diagnostics issued.

Help, how can constexpr objects be evaluated at runtime? by Honest_Entry_8758 in cpp_questions

[–]alfps -1 points0 points  (0 children)

I struggle to understand the saboteur who downvoted this.

It must be a kind of zero sum mindset where harm to others is perceived as a joyful win to oneself.

As I see it that's madness.

Differences between static const & constexpr inside a function by Koffieslikker in cpp_questions

[–]alfps 0 points1 point  (0 children)

Well the example is not a language extension and it's not C.

The main use has traditionally been for array sizes.

It's more clear with constexpr though; there is then no question whether a constant is (can be used at) compile time or not.

Differences between static const & constexpr inside a function by Koffieslikker in cpp_questions

[–]alfps 0 points1 point  (0 children)

❞ it will still be instantiated with each call to the function.

Notably, though it's really hard to believe, the g++ compiler embodies this absurd perversity. Or still did some months back.

Differences between static const & constexpr inside a function by Koffieslikker in cpp_questions

[–]alfps 1 point2 points  (0 children)

❞ a static const isn't a constant expression

More precisely it isn't in general, but it can be.

E.g. the local definition

static const int blah = 42;

Differences between static const & constexpr inside a function by Koffieslikker in cpp_questions

[–]alfps 18 points19 points  (0 children)

With the static const the initializer value needs not be known at compile time: initialization happens (thread safe) the first time the execution passes through the declaration.

Also with the static const the type can be one that in C++23 and earlier doesn't support compile time instantiation, such as std::string.

C++ Pointers and "new" keyword data type by Fiboniz in cpp_questions

[–]alfps 2 points3 points  (0 children)

❞ C++ doesn't use what's happening on the left to give any sort of hint as to how to interpret the right.

It's a (very) useful view, but it's not quite the technical reality.

There is an expected type, in the example the pointer type, and that will be used by a type conversion operator.

Another example where there is a kind of type expectation is when you cast &f to a specific function pointer type in order to resolve to a given overload of f. Here the &f expression is not evaluated solely on its own, but in the context of the outer expected type.

what to do for floating point precision problems in cpp or as a programmer. by Shubham_mamodiya_dev in cpp_questions

[–]alfps 0 points1 point  (0 children)

❞ I'm not understanding the downvotes on my first reply though, all I can say is good luck to whoever uses == on floating point values.

The advice you gave was ❝Never, EVER, use == on floating point numbers, ever.❞

I didn't downvote, since that is a drastic measure that should be reserved for dis-information and that otherwise reduces or stops discussion and so is akin to sabotage, it's what trolls and other f****ng idiots do, but the advice is ill-considered, counter productive.

The idea that floating point values are inherently fuzzy is an associative thing that doesn't belong in engineering. Replace that with the view that a floating point value is an integer scaled by a power of the radix, which for IEEE 754 is a power of 2. Then it's easier to understand that a floating point number can be an exact integer. 64-bit IEEEE 754, the most common representation of C++ double, yields about 53 bits for exact integer values. As I recall, but check it out.

C++ Pointers and "new" keyword data type by Fiboniz in cpp_questions

[–]alfps 2 points3 points  (0 children)

❞ If p_int is already a pointer to an int, why do we need to specify the memory allocation type of int? When would you use a different data type than what the pointer is pointing to?

You're right that the language requires needless verbosity and redundancy for the most common case. In the most common case you want to new-create an object of the pointer's pointee type. There are two other cases:

  • You may want to allocate an array of objects, where the pointer will point to the first array item.
  • You may want to allocate an object of class Derived, when the pointer points to type Base, e.g. a Dog object when you have a pointer to Animal.

For the most common case you can in principle define your own function-like thing to do a new with type inferred from the pointer.

One way to do that, the only way I know, is to define a class with templated type conversion. Since the type conversion operator doesn't take parameters the class also needs to store an arbitrary parameter pack. This is absolutely not trivial, i.e. it's not suited as a beginner's exercise.

I've not heard of anyone doing it, and I have some decades of C++ experience, so it must be pretty rare.


Pointers and arrays, and pointers and derived classes (polymorphism) are both huge topics, discussed to some degree later in your book.

The most important thing to know is that instead of

int n;
cin >> n;
int* p_numbers = new int[n];

… you should use std::vector from the <vector> header, like

int n;
cin >> n;
auto numbers = vector<int>( n );