开发者

In C can I declare a constant character array?

I am working on a character string to signify a change in sign. I have had success with the character string that's commented out below, but would prefer a simple if-else statement using开发者_高级运维 constant character arrays UP = "up/0/0" and DOWN = "down".

Does anyone know a simple way to declare such constant values?

    char direction[5]; // declares char array to signify sign change    
    if (value - price1 > - 0.005) { // adjusts for noise near 0
        direction = UP;
    }
    else direction = DOWN;

    // update price-change direction string
//      if (value - price1 > - 0.005) { // adjusts for noise near 0
//          direction[0] = 'u';
//          direction[1] = 'p';
//          direction[2] = 00; // set character to null value
//          direction[3] = 00;
//      }
//      
//      int[4] var_name 
//      else {
//          direction[0] = 'd';
//          direction[1] = 'o';
//          direction[2] = 'w';
//          direction[3] = 'n';
//      }


If you're not modifying the string later, you could do it like this:

const char *direction:
if (value - price1 > - 0.005) { // adjusts for noise near 0
    direction = UP;
}
else
    direction = DOWN;


You can't assign like that, but you can do:

strcpy(direction, UP);

strcpy(direction, DOWN);

Obviously, be careful not to overflow your buffer. If those are the only possible sources, you're fine.


Consider using:

const char up_string[] = "UP";
const char down_string[] = "DOWN";
char *direction;
direction = (value - price1 > - 0.005) ? up_string : down_string;

You could then have direction simply be a pointer to either of those locations (as opposed to using strcpy).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜