Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement not effective

void spriteput(int x,int y, int stype)
{
    char sprite1[5]="OOOO";
    char sprite2[5]="OOOO";
    char sprite3[5]="OOOO";
    char sprite4[5]="OOOO";
    if (stype == 1)
    {
        char sprite1[5] = " OO ";
        char sprite2[5] = "OOOO";
        char sprite3[5] = "OOOO";
        char sprite4[5] = " OO ";
        mvprintw(2,y,"%s \n",sprite1);
    }
    mvprintw(x+1,y,"%s \n",sprite2);
    mvprintw(x+2,y,"%s \n",sprite3);
    mvprintw(x+3,y,"%s \n",sprite4);
}

If I'm correct that block of code should print out on a NCURSES screen

 OO  
OOOO
OOOO
 OO

Instead however, it prints out the default text (the first char statements). Can anyone tell me why this is? The printw statement inside the If-block prints out the proper text, so it's being assigned correctly. Thank you in advance.

like image 320
Galileo Avatar asked Apr 17 '26 08:04

Galileo


2 Answers

Your declarations inside the if statement are shadowing the declarations outside it; once the if-statement exits, those shadowed declarations are out of scope and gone forever.

To work around this, you could do something like

if (stype == 1)
{
    sprite1[0] = ' ';
    sprite1[3] = ' ';
    // ...

Or you could use a function like strcpy to accomplish the same thing.

This is a situation where compiling with full warnings turned on would have shown you the error without needing to post here, by the way.

like image 53
Mark Rushakoff Avatar answered Apr 20 '26 04:04

Mark Rushakoff


You're declaring them as local variables in the 'if' block. They don't affect the strings in function scope.

like image 22
Fred Larson Avatar answered Apr 20 '26 05:04

Fred Larson