Amir Khasru Amir Khasru - 4 months ago 11
C Question

Is it legal to use non-whitespace characters betwen field specification? If it's okay, then what is the output we can expect?

#include<stdio.h>

main(){

int a,b,c;
scanf("%d-%d",&a,&b);
c=a+b;
printf("%d",c);


}


What is the output we can expect from this code?

Answer

Yes, using not whitespace characters in a scanf format string is legal. Those characters are expected to be read and skipped over. If those characters are not given in the input, scanf stops reading at that point.

For example, if your input was 3-4, the 3 would be stored in a, the - would match the pattern, and the 4 would be stored in b so the output would be 7.

If on the other hand you inputted 4x5, the 4 would be stored in a but the x would halt reading of further input because it does not match -. Then b would have an undefined value and the result of adding a value to it would also be undefined.

Comments