1

I am having trouble compiling some very simple C++ code on my Raspberry Pi B+. I wrote the following program in a file called test.cpp

    #include <stdio.h>
    #include <stdint.h>

    // define type scalar
    typedef int64_t scalar;

    // class definition 
    class Point {
         public:
            Point(
               scalar x, // input
               scalar y  // input
            );

            void print_point();

         private:
               scalar x;
               scalar y;
    };

    // class methods
    Point::Point(scalar x, scalar y) 
    {
        this->x = x;
        this->y = y;
    }

    void Point::print_point()
    {
        //print (x,y)
        printf("(%d,", x); printf("%d)\n", y);
    }



    // main
    int main()
    {
        scalar a = 5;
        printf("%d\n", 5);

        Point* A = new Point(5,1);
        A->print_point();

        return 0;
    }

I compile this code with the following command:

    g++ -o test test.cpp

when I compile the code in my linux computer, the program works fine and it prints out:

    5
    (5,1)

The problem is that when I do the exact same thing on my Raspberry Pi, the programs prints out:

    5
    (23867400,67288)

Do you have any idea why ? How can I fix this problem ?

1 Answer 1

2

It is because that you passed the wrong type of argument to printf. When the format given to printf is "(%d," or "%d)\n", the second argument is expected to be int. You gave it long int. For variable argument list,

If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases:

— one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types;

— one type is pointer to void and the other is a pointer to a character type.

If you want to print x and y in decimal to stdout, you should change

printf("(%d,", x); printf("%d)\n", y);

to

printf("(%ld,%ld)\n",x,y);

or use iostream.

#include <iostream>

std::cout << '(' << x << ',' << y << ")\n";
2
  • Why does the first printf that prints only the 5 work?
    – PaulF8080
    Jun 24, 2016 at 8:23
  • @PaulF8080 Because you used it correctly. 5 is of type int.
    – v7d8dpo4
    Jun 24, 2016 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.