Is this legal?

New to FreeBASIC? Post your questions here.
Post Reply
PeterHu
Posts: 159
Joined: Jul 24, 2022 4:57

Is this legal?

Post by PeterHu »

Is below if statement legal?Thanks in advance.

Printing result:"myByte contains 8"

Code: Select all

	dim as integer myByte= 6
	if myByte and 8 = 8 then
		print "myByte contains 8"
	else
		print "myByte does not contain 8"
	end if


marcov
Posts: 3462
Joined: Jun 16, 2005 9:45
Location: Netherlands
Contact:

Re: Is this legal?

Post by marcov »

Probably parenthesis due to C style auto testing integers for 0 and same worth for bitwise and logical AND.

I.e. (mybyte) and (8=8) vs (mybyte and 8 )=8
Last edited by marcov on Jan 31, 2024 14:58, edited 1 time in total.
fxm
Moderator
Posts: 12132
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Is this legal?

Post by fxm »

In the Operator Precedence documentation page, you can see that the '= (equal)' operator (do not confuse with the assignment operator) has a precedence higher than the 'And' operator.

So:
'if myByte and 8 = 8 then'
is parsed as:
'if (myByte) and (8 = 8) then'.

To go against the operator precedence, you must insert parentheses:
'if (myByte and 8) = 8 then'
PeterHu
Posts: 159
Joined: Jul 24, 2022 4:57

Re: Is this legal?

Post by PeterHu »

Thank you both.

This is great the language does not require that the parentheses are mandatory in IF statement unless certain situation takes place.
angros47
Posts: 2326
Joined: Jun 21, 2005 19:04

Re: Is this legal?

Post by angros47 »

You can also replace "and" with "AndAlso" (that is more appropriate, in such a situation, actually)

Original BASIC used bitwise AND as logical AND, as well, and it didn't make a real difference because it was supposed to work mostly with variable comparisons. But when used with function results, using logical or bitwise operator produces different results
PeterHu
Posts: 159
Joined: Jul 24, 2022 4:57

Re: Is this legal?

Post by PeterHu »

angros47 wrote: Feb 02, 2024 18:40 You can also replace "and" with "AndAlso" (that is more appropriate, in such a situation, actually)

Original BASIC used bitwise AND as logical AND, as well, and it didn't make a real difference because it was supposed to work mostly with variable comparisons. But when used with function results, using logical or bitwise operator produces different results
Thank you!!
Post Reply