1,032 views
0 votes
0 votes
printf("%d",20/3.2); or printf("%i",20.0/3);     or %u     // why does it prints garbage value

Could someone explain(or provide info) about format specifiers %d, %s, %f.... in detail in C

2 Answers

3 votes
3 votes
C language is meant for writing high performance code and one is expected to write codes with proper meaning. It is not having error supporting feature like Java -- which makes it less robust but it can run much faster. Now coming to the question, C mandates that if we use any format specifier in printf and pass a different type as the corresponding argument, behaviour is undefined. i.e., if "%d" is used, passed value must be an integer (char is also of type integer). Here, 20/3.2 returns a double value because "3.2" is double and for any operation, the result will be of the largest type involved in the operation. 20/3 would give correct answer of 6. Otherwise use an explicit type casting with (int) (20/3.2)
1 votes
1 votes

%s  $\Rightarrow$ sequence of characters.

 For reading and printing, integer values using scanf() and printf() function, either %i or %d is used but there is a subtle difference in both %i and %d format specifier.

%d specifies signed decimal integer while %i specifies integer.

while using scanf()

%d always takes base 10

%i auto detects the base means it can take octal, decimal or octal numbers. For octal input just write 0 with the input number like 012 and for hexa values put 0x like 0x12.

%d and %i behave similar with printf

https://ide.geeksforgeeks.org/C68BEND7Hl

Related questions

0 votes
0 votes
2 answers
1
Debargha Mitra Roy asked Apr 10
104 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
3 votes
3 votes
3 answers
2
Laxman Ghanchi asked May 19, 2023
1,160 views
#include<stdio.h void print(int n) { printf("Hello "); if(n++ == 0) return ; print(n); n++; } int main() { void print(); print(-4); }How many times printf execute?? And H...
0 votes
0 votes
1 answer
3
Laxman Ghanchi asked May 19, 2023
685 views
#include<stdio.h>void print(int n){ printf("Hello "); if(n++ == 0) return ; print(n); n++;}int main(){ void print(); print(-4);}