[chbot] Pop quiz C

Mike Field hamster at snap.net.nz
Wed Apr 26 05:31:06 BST 2017


Sorry Volker - till I hit the problem I agreed with with you, but Paul 
is indeed correct - it is undefined and the compiler and hardware can do 
whatever the heck they want, and they don't even have to agree about 
what they do when on a given platform.

It doesn't matter if the target is 8, 16, 32 or 64 bits - it will be 
none-zero, and with "-Wall -pedantic" no errors are emitted for the 
following code (at least with GCC).

$ cat check.c
#include <stdio.h>

int main(int argc, char *argv[])
{
   int a;
   long long b;
   int n0 = 34;
   a = 0xFFFFFFFF;
   a = a << n0;
   printf("%08X\n",a);

   b = 0xFFFFFFFF << n0;
   printf("%016llX\n",b);
}
$ gcc -o check check.c -Wall -pedantic
$ ./check
FFFFFFFC
00000000FFFFFFFC



On 26/04/2017 2:25 PM, Volker Kuhlmann wrote:
> On Wed 26 Apr 2017 10:04:47 NZST +1200, Michael Field wrote:
>
>> What is the value of a?
>>
>>   a =
>> 0xFFFFFFFF << 34;
> The language is C, so it's pretty easy, however you failed to specify
> all parameters, hence the options are:
>
> 1) a is not even declared, so that trashes the challenge as "doesn't even
> make the syntactically correct" threshold. Assuming int only gets that
> far, as int may be 64 bits. So:
>
> 2) a is 64 bits, 0xFFFFFFFF is type int(!!! as you didn't say
> otherwise): The result is 0xFFFFFFFC00000000. Or at least I think shifts
> in C are always logical, if not, the result should be
> 0xFFFFFFFFFFFFFFFF.
>
> 3) a is 32 bits, 0xFFFFFFFF is type int (thus -1), the result is a=0
> unless shifts are signed for signed numbers (int is signed, the type of
> a only matters after the shift expression is evaluated).
>
> Contrary to another reply, I don't see why the result in 3) is
> undefined. The mathematics are exactly defined. Stupid programming is
> entirely different to defined mathematics. -Wall -pedantic should
> *always* be present to have a chance of a hint to said stupid
> programming. The compiler's job is not to make sure your program works,
> it is to translate your program exactly as given, its warnings can't do
> more than kick the derriere of the area between keyboard and chair
> ("left shift exceeds width of type").
>
> The compiler is however allowed to conclude, after due optimising
> considerations, that the result is always 0 (or -1), and remove all
> expressions deemed constant, and replace them with a constant, that
> being an exact result of your program as given.
>
>> Have you checked your answer?
> No. Any results or issues I missed? ;-)
>
> Volker
>




More information about the Chchrobotics mailing list