Somewhat StackOverflow Thread

Here, you can post a piece of code and ask questions about it. That way, the misc thread won’t be flooded with coding questions. Here’s my first question : in the following code, which is written in C++, if the for loop does return false, will it end the function or will it try to return true afterwards?

bool isNotNumber(char inputCharacter)
{
    char numbersArray[10] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
    for (unsigned int i = 0; i <= 10; i++)
    {
        if (inputCharacter == numbersArray[i])
        {
            return false;
        }
    }
    return true;
}
1 Like

return will always exit the current function immediately. Only one return statement can be executed as the first one exits the current function right away and execution resumes where the function was called from.

This applies to at least C++, C, C# and Java. Basically any programming language that has the return keyword will immediately stop executing the current function. I’d be very surprised to learn that there was a programming language that broke that extremely common pattern.


Just for fun, here’s a few advanced concepts that are basically “but wait”:

  • In C++ all local objects with automatic storage duration (think function local variables) must be destructed before leaving the scope. So what actually happens when return is executed is that the function prepares the return value, runs the destructors for all local objects, and only then jumps back to the function’s caller to continue the program. As a fun side effect of this you can “prevent” the return by throwing an exception from one of the destructors. I don’t think that’s very useful as if I remember right an exception escaping from a destructor is the same as calling std::abort. But technically by throwing an exception from a destructor you would prevent the normal return method from working. So if anyone asks does return always get you back up the callstack, the answer is that technically no.

  • In C# methods can return an iterable to only calculate the next return value when the caller needs it (for example you can make a method that returns an infinite list of numbers). And with this syntax the current method execution does continue so that you can return multiple return values as an iterable: yield return value; (to actually stop the method execution early you can use yield break).

Anyway you don’t need to know any of this when starting out, but I just wanted to highlight how even quite simple functionality can have more in-depth things related to it that someone might encounter on their programming career.

2 Likes

What hhyyrylainen said, but I must note that if the inputCharacer is not equal to one of the members of numbersArray, you will at some point read the byte numbersArray[10], which is out of bounds and may give the wrong result if the byte after the end of numbersArray is equal to inputCharacter. This is an off-by-one error that can be fixed by rewriting the loop as

    for (unsigned int i = 0; i < 10; i++)
    {
        if (inputCharacter == numbersArray[i])
        {
            return false;
        }
    }

Other languages such as java or python give you an error if you try to access an element that is out of the bounds of an array, but in C++ and in C the program will do whatever it wants , which normally means that it will try to read the data at that memory location, which may result in a segfault or some other unexpected behaviour.

2 Likes

My bad, that was a typo in my program. Thanks for the info!

EDIT: @hhyyrylainen, I recall that you’ve once said that it was a good practice of using std:: instead of using namespace std;. Why?

Because it is only good for toy example programs. So it is a good habit to learn to do it properly from the start. Eventually you will work on a large program where you might have 3-4 different things called vector and the only way to sensibly work there is using namespaces. If you have seen big C projects they basically have to emulate namespaces by prefixing each of their method names with their library name. Now that is super tedious, but luckily us C++ programmers have modern language features like namespaces. If you need to type a really long namespace multiple times in a method / file you can define a shorter alias for it like using fs = std::filesystem and then just use fs::exists for example.

Is there a way to push commits from local to remote repo’s branch?

Yes. Assuming your commits are on my-branch, you can simply run

git push origin my-branch
1 Like

If I construct a string using string (const string& str);, which copies the string str, can I delete str afterwards without affecting the copy or is the copy actually a reference?

Update: Yes, it is possible apparently.

I mean even if the string was a reference (which btw is not how the std library works but another string library could work like that) you assigning a new value to the string should make food reference the new value, but wouldn’t affect the reference in meal. Calling clear() on the string would actually tell you if two variables referenced the same data and clearing one would clear both.

Can I make a class with “custom” variables that I could utilize like this:

//              This is the class
//                      v
if (buildingStep == BuildingSteps.NearlyCompleted)
    ...

Or anything like that?

Do you mean like an enum?

public enum BuildingSteps
{
    Pending,
    Started,
    NearlyCompleted,
    Completed
}
1 Like

Can I make Forms text labels support Markdown or BBCode? (Visual Studio)

It depends on more the GUI framework you use rather than the coding environment. It’s more likely there is a rich text editing control available. Or did you mean like you write markdown in a text box and see a live preview of it somewhere else? That’s much more doable with basic tools.

1 Like

Something that would work similiar to forums’ post-writing text box thing (does it have a name?). In left text box I write raw text with various tags and symbols and in right there is already Markdown’ed text.


Edit:
Actually I don’t need specifically that, but something that would just “translate” Markdown into stylized text.

That sounds like you need a markdown parser that supports converting that to a rich text format supported by the GUI framework you are using. It might be easier to find a customizable bbcode parser that you can adjust yourself if a premade solution cannot be found. For example, I found this for the GUI framework the Thrive Launcher uses to render markdown text: GitHub - whistyun/Markdown.Avalonia: render markdown with Avalonia UI

1 Like