Thread: Operating a long int with an int is not working

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    2

    Operating a long int with an int is not working

    Hello,
    I'm having trouble trying to operate with long int and int variables. The long int variables are stored in an array, and when I print an operation like this:
    Code:
    #include <stdio.h>
    
    int main(void) {
        long int numbers[3] = {1, 2, 3};
        printf("%ld\n", ((numbers[2] * numbers[2]) - (4 * numbers[1] * numbers[3])));
        return 0;
    }
    I'm getting results like -6855564848099805175 or 5150792580894394377.

    Type casting is not working either:
    Code:
    #include <stdio.h>
    
    int main(void) {
        long int numbers[3] = {1, 2, 3};
        printf("%ld\n", (long int)((numbers[2] * numbers[2]) - (4 * numbers[1] * numbers[3])));
        return 0;
    }
    Why is the operation not being done successfully?
    I'm using GCC 7.3.0.

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    790
    Array indices start at 0. An array with 3 elements is indexed with 0, 1, and 2. An index of 3 is outside the array.
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

  3. #3
    Registered User
    Join Date
    Mar 2019
    Posts
    2
    Oh dear! I cannot believe I made that mistake. Definitively assigning the values 1, 2 and 3 to the array elements confused me.

    Thank you very much for your help, john.c.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 128 bit (long double) printf not working
    By AamirYousafi in forum C Programming
    Replies: 25
    Last Post: 07-10-2016, 08:59 PM
  2. Replies: 16
    Last Post: 06-07-2015, 03:28 PM
  3. <Winsock> connect() taking too long/never working.
    By darkAlly in forum Networking/Device Communication
    Replies: 0
    Last Post: 05-26-2014, 10:09 AM
  4. printf not working with long type
    By that_guy1 in forum C Programming
    Replies: 2
    Last Post: 10-15-2005, 05:37 PM
  5. How long have you guys been working with C/C++??
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 24
    Last Post: 08-01-2003, 03:41 PM

Tags for this Thread