Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

c - bool function that modifies the values of pointers and returns true or false

I've written the following function:

bool order(int * a, int * b){
    int temp = *a;
    if(*a > *b){
     *a = *b;
     *b = temp;
     return true;
    }
    else if(*a < *b){
     *a = *a;
     *b = *b;
     return false;
    }
    else if(*a==*b){
     *a = *a;
     *b = *b;
     return false;
    }
}

What I'm trying to do is take in 2 arguments int * a and int *b. Afterwards, the function is meant to modify the values of a and b so that after the function is run through, a is now the smaller of the two and b is the larger of the two - i.e (*a <= *b). If *a<= *b is already true, I want it to return false since the function didn't have to modify the values, but if it is not true and the function did have to modify the values I'd like it to return true. Currently when I run this, nothing is being returned neither false or true. Is this supposed to happen? I've programmed in python before and when I used return True; or return False; in a function it would return either True/False. Or did I make a programming mistake and that's why the values aren't being modified so nothing is being returned. Any help would be appreciated.

question from:https://stackoverflow.com/questions/65939303/bool-function-that-modifies-the-values-of-pointers-and-returns-true-or-false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assigning a variable to itself makes no sense. Also if you compile your program with warnings enabled it will complain about missing return statement due to missing else clause containing a return statement (or a return statement after the if statement). This should be sufficient:

#include <stdbool.h>

bool order(int *a, int *b)
{
    bool swapNeeded = *a > *b;
    if (swapNeeded) {
        int oldA = *a;
        *a = *b;
        *b = oldA;
    }
    return swapNeeded;
}

This version also has a single exit point which in general makes it easier to reason about and debug a function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...