sid_com
sid_com

Reputation: 25117

"Inline C"-question

#!/usr/bin/env perl
use warnings;
use 5.012;
use Inline 'C';

my $value = test();
say $value;

__END__
__C__
void test() {
    int a = 4294967294;
    Inline_Stack_Vars;
    Inline_Stack_Reset;
    Inline_Stack_Push( sv_2mortal( newSViv( a ) ) );
    Inline_Stack_Done;
}

Output:

-2

Why do I get here an output of "-2"?

Upvotes: 5

Views: 276

Answers (2)

ysth
ysth

Reputation: 98398

Perl supports both signed and unsigned integers, and its operators will switch nicely between them, but you are explicitly requesting an IV (signed int type SV). Use newSVuv instead. You also need to say UV a = or unsigned a = instead of int if ints are 32 bits but perl is using 64 bit integers, since otherwise the cast to UV done by newSVuv will end up extending the sign bit through the upper 32 bits.

Upvotes: 5

Benoit
Benoit

Reputation: 79205

int a uses probably 32-bit representation. You should use unsigned int if you want to represent values above 4,294,967,296/2.

Upvotes: 5

Related Questions