Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch if else statement not working

I'm writing a little program but I have a problem with an if else statement.

@echo off 
set /p points= 
echo %points% 
echo 1x5= 
set /p 15= 
if %15%==5 ( 
    echo well done! 
    set /a points=%points%+1 
) else ( echo wrong! )
pause 
echo %points% 
pause

Even if I fill in a wrong answer, it still ads 1 point to my points and says "Well done!"

(BTW: got some problems with inputting the code, don't now if you will be able to read it)

like image 849
Cecemel Avatar asked Mar 07 '26 21:03

Cecemel


1 Answers

When an argument is included in the command line when calling the batch file, it is referenced from code as %1, %2, ... for the first, second, ... parameters.

In your code, when you write if %15%==5 ..., %15% is interpreted as first parameter to batch file (%1) followed by a 5 and a non escaped non paired percent sign that is discarded by the parser. So, if the batch file has no input arguments and %1 is empty, your if code is executed as if 5==5 ...

As a general recomendation, variables in batch files "should" never start with a number, as they will be considered as input arguments.

like image 142
MC ND Avatar answered Mar 10 '26 11:03

MC ND