dropdropdrop
dropdropdrop

Reputation: 39

Why can't I use "long long int" with "int" in my C code?

Why can't I use "long long int" with "int" in my C code?

int main(void) {
    long long int a;
    int b;
    a = 1000000000;
    b = 3200;
    printf("long long int a = %d\n int b = %d", a, b);
    return 0;
}

long long int a = 1000000000

int b = 0

Upvotes: 0

Views: 826

Answers (5)

autistic
autistic

Reputation: 15642

There are two possible reasons.

  • Firstly and most importantly, I see no evidence of your compiler and/or standard library supporting C99, and hence no evidence of your compiler and/or standard library supporting long long int and the corresponding format specifier %lld.
  • Secondly, you're lying to printf about the type of a; %d tells printf that the argument is of type int, even though it isn't (it's long long int). You should be using %lld...

Technically both of these would invoke undefined behaviour; using %d when your argument isn't an int is UB and even if you were to correctly use %lld you'd be using an invalid format specifier in C89's scanf (%lld is a C99 format specifier) and invoking UB as a result.

Have you considered using Clang in Visual Studio?

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

You have to use the correct format specifier in the printf function

printf("long long int a = %lld\n int b = %d", a, b);

Otherwise the function behaviour is undefined.

It seems that in the given situation the function considers the value of the long long int object pushed on the stack of the function as an argument like two objects of type int.

Upvotes: 2

icecity96
icecity96

Reputation: 1227

C99 standard says: If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined The type of a is long long int but you use %d to print it.

Upvotes: 1

Gopi
Gopi

Reputation: 19864

Using wrong format specifier leads to undefined behavior the right format specifier to print out a long long int is %lld

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

You can try this:

printf("long long int a = %lld\n int b = %d", a, b);

%d is used to refer int. If you want to refer long long int then you have to use %lld

Upvotes: 2

Related Questions