簡體   English   中英

c函數,在每次調用時返回不同的值

[英]c function that returns different values on each call

我正在研究atmel編程,我正在嘗試創建一個程序,其函數返回一次為true的布爾值,第二次為false,取決於之前是否調用,或者不是第一次返回true第二個它返回false,我會使程序像::

if(boolean == true){

//execute the code if the button is pressed for the first time

//switch on a led


}else{

//execute the code if the button is pressed for the second time

//turn off the led

}

功能就像::

bool ledToggle(){

if(function is called for the first time)

return true;

}else{

return false;

}

您可以為此使用靜態標志,例如

bool ledToggle()
{
    static bool state = false;

    state = !state;

    return state;
}

函數內的靜態變量會記住函數調用之間的值:

bool ledToggle()
{
    static bool led_is_on = false;

    led_is_on = !led_is_on;
    return led_is_on;
}

這將使每個調用的結果翻轉為true和false。

如果您的編譯器支持它( STDC_NO_ATOMICS C11),則使用:

#include <stdatomic.h>

bool ledToggle()
{
    static atomic_int state; // initialised to zero by default
    state ^= 1; // XOR is atomic, state = !state is not atomic.
    return state; // rely on implicit cast to bool
}

這將是線程安全的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM