PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label return-value. Show all posts
Showing posts with label return-value. Show all posts

Tuesday, November 15, 2022

[FIXED] What is std::expected in C++?

 November 15, 2022     c++, c++-faq, error-handling, return-value, std-expected     No comments   

Issue

In one of the most respected stackoverflow answer I found an example of std::expected template class usages: What are coroutines in C++20?

At the same time I cannot find any mentioning of this class on cppreference.com. Could you please explain what it is?


Solution

Actually, the best way to learn about std::expected is a funny talk by the (in)famous Andrei Alexandrescu: "Expect the Expected!"

What std::expected is, and when it's used

Here are three complementing explanations of what an std::expected<T, E> is:

  • It is the return type of a function which is supposed to return a T value - but which may encounter some error, in which case it will return a descriptor of that error, of type E.

    An example:

    std::expected<ParsedData, ParsingError> parse_input(Input input);
    
  • It's an error-handling mechanism, being an alternative to throwing exceptions (in which case you always return the value you were supposed to), and to returning status/error codes (in which case you never return the value you want to, and have to use an out-parameter).

    Here are the two alternative error-handling mechanisms applied to the function from the previous example:

    ParsedData    parse_input_2(Input input) noexcept(false);
    ParsingError  parse_input_3(ParsedData& result, Input input);
    
  • It's a discriminated union of types T and E with some convenience methods.

"How is it better than just an std::variant<T,E>?"

It behaves somewhat like std::optional<T>, giving focus to the expected, rather than the unexpected, case:

  • result.has_value() - true if we got a value rather than an error.
  • if (result) - checks for the same thing
  • *result - gives us the T value if it exists, undefined behavior otherwise (same as std::optional, although many don't like this).
  • result.value(), gives us the T value if it exists, or throws otherwise.

Actually, that last mode of access behaves differently than std::optional if we got an error: What it throws is a bad_expected_access<E>, with the returned error. This behavior can be thought of as a way to switch from expected-based to exception-based error-handling.

"Hey, I looked for it in the standard and it isn't there!"

std::expected will be part of the upcoming C++23 standard. The proposal (P0323) has recently been accepted.

This being said - it is quite usable already, since it requires no new language facilities. I would recommend Sy Brand (tartanllama)'s implementation, which can be used with C++11 or later. It also has some neat functional-style extensions (which may not be standardized).



Answered By - einpoklum
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 19, 2022

[FIXED] Why is my function not returning the expected result?

 October 19, 2022     function, return, return-value, rust     No comments   

Issue

My function is not returning the expected result. It's giving 0 instead of 2, that is the result of 1 + 1. Why is this happening and what could I do to fix it? Here is the code:

// Calculate the weight of a building

fn main() {
    let weight = sum(1, 1); //calling sum(1,1) and trying to bind its result to a variable
    println!("The result is {}.", weight); //printing "weight"
}

//function to perform "beams + columns" and use it in main()
fn sum(beams: u32, columns: u32) -> u32 {
    let beams: u32 = 0; 
    let columns: u32 = 0;

    beams + columns //Trying to return the result
}

Solution

You have created two variables that initalized to 0 in function sum, hence the result being 0.

You should delete these two variables in order to get the correct result.



Answered By - imilano
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 5, 2022

[FIXED] How to return a value from try, catch, and finally by using condition?

 August 05, 2022     conditional-statements, exception, java, return-value, try-catch     No comments   

Issue

My get() method is being marked with a red line, it tells me

this method must return a result of type char

public char get() {
    mutex.lock();
    char c = buffer[out];
    try {
        while (count == 0) {  
            okConsume.await();
        }
        out = (out + 1) % buffer.length;
        count--;
        System.out.println("Consuming " + c + " ...");
        okConsume.signalAll();
        return c;
    }catch(InterruptedException ie) {
        ie.printStackTrace();
    }finally {
        mutex.unlock();
    }
    
}

Solution

Your code should cover all the possible scenario. Now it doesn't because you're not returning from the method if exception occur.

The return statement placed inside the try will be unreachable in case of exception.

For more information on Exception-handling, I suggest to have a look at this tutorial.

There are two ways to fix it:

  • place return statements in both try and catch blocks;
    public char get() {
        mutex.lock();
        char c = buffer[out];
        try {
            // some code
            return c;
        } catch (InterruptedException ie) {
            ie.printStackTrace();
            return c;
        } finally {
            mutex.unlock();
        }
    }
  • place the return statement after the finally block;
    public char get() {
        mutex.lock();
        char c = buffer[out];
        try {
            // some code
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        } finally {
            mutex.unlock();
        }
        return c;
    }


Answered By - Alexander Ivanchenko
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 30, 2022

[FIXED] How do I may a simple statement if not ABCD error message. Also I am having problems getting the number of questions requested returned

 July 30, 2022     python, return-value, validation     No comments   

Issue

I am new to python and am trying to do two things that are not working.

The first is return the number of questions a person asks for (I have got my error messages done.

The second I want an error message if the user does not enter exactly A,or B,or C, or D. I have set it so they can't leave it blank and tried to do it so that if they enter a number they get an error message. I just want to add that they can't add characters or letters e-z or lower case.

def playquiz(): 
    print ("How many questions would you like to answer?")
    numberofquests =input()
    numberofquests = int(numberofquests)

    if numberofquests > 15:
     print ("there aren't that many questions. The maximum you can answer is 15!")
     print ("How many questions would you like to answer?")
     numberofquests =input()
     numberofquests = int(numberofquests)

    if numberofquests <=0:
     print ("Good bye")
     exit (0)
     
playquiz()


# -------------------------
def new_game():
    
              
    guesses = []
    correct_guesses = 0
    question_num = 1


    for key in questions:
        print("-------------------------")
        print(key)
        for i in options[question_num-1]:
            print(i)
        guess = input("Enter (A, B, C, or D): ")
        guess = guess.upper()
        guesses.append(guess)

        while guess ==(""):
            print ("Can't leave this empty")
            guess = input("Enter (A, B, C, or D): ")

        while guess == isalpha():
            print ("You must enter either A,B,C,D")

        correct_guesses += check_answer(questions.get(key), guess)
        question_num += 1

    display_score(correct_guesses, guesses)

Solution

Try this:

numberofquests = int(input("How many questions would you like to answer?")) 
print(numberofquests)


Answered By - bezootje
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 5, 2022

[FIXED] Returning current URL in WordPress

 February 05, 2022     php, return-value, url, wordpress     No comments   

Issue

I am trying to implement canonical and hreflang tags in WordPress, but I cannot retrieve the current URL of the visited page.

I tried :

 <?php echo site_url(); ?>

But it returns https://www.example.com instead of https://www.example.com/current-page1


Solution

In case anyone else needs this. Below code should get the exact URL including parameters.

home_url($_SERVER['REQUEST_URI']);

You can echo or return it depending on your use case. e.g.

echo home_url($_SERVER['REQUEST_URI']);

or

return home_url($_SERVER['REQUEST_URI']);


Answered By - Sadiq11111
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing