in reply to testing for undef in perl XS code (in DBD::ODBC)

The right way to test for undef in XS code is using !SvOK(sv).

PL_sv_undef is a perl scalar with the undef value, but it is not the only one. It is just for convenience, to not have to instantiate a new scalar on every place where an undef is required.

sv_undef is a macro that expands to PL_sv_undef

Replies are listed 'Best First'.
Re^2: testing for undef in perl XS code (in DBD::ODBC)
by mje (Curate) on Nov 06, 2007 at 11:23 UTC
    I'm finding
    if(valuesv == &sv_undef)
    never tests true and
    !SvOK(valuesv)
    tests true when valuesv is undef - of course. What I'm not sure is what the original author might have meant by the first test above - perhaps it should have been SvOK in which case it was bug, perhaps something else.
      I have a question about this:
      use warnings; use strict; use Inline C => Config => BUILD_NOISY => 1; use Inline C => <<'EOC'; SV * create_undef() { return newSVsv(&PL_sv_undef); } void is_defined(SV * x) { //x = &PL_sv_undef; x == &PL_sv_undef ? printf("Not defined\n") : printf("Defined\n") +; } EOC my $undef = create_undef(); is_defined($undef);
      Note that $undef is created (by 'create_undef()') with the value &PL_sv_undef, and that the 'is_defined()' function then tests to see whether $undef == &PL_sv_undef. Amazingly, 'is_defined()' reports that $undef != &PL_sv_undef (by stating that $undef is defined).

      But if you uncomment that one line of C code that is excluded in the above script, then you find that $undef == &PL_sv_undef (as 'is_defined()' now states that $undef is undefined).

      I think we're dealing with the fact &PL_sv_undef is the value associated with a certain memory location, and that the value associated with a certain memory location changes from one function to the next. salva (or anyone else, for that matter), is that a valid approximation of what's happening ?

      Cheers,
      Rob
        PL_sv_undef is a perl scalar that has the value undef.

        There can be other perl scalars with the undef value. Actually, you can create then using SV *a = newSV(0).

        With a == &PL_sv_undef you are not testing if they contain the same value but if they are both pointers to the same scalar!

      oh, I am pretty sure it is a bug!