Can I use scanf(...) as argument to a function ?
Like this:
printInteger(scanf(....));
Can I use scanf to attribute the value that I read to some variable ?
Like this:
n = scanf(...);
p.s.: Here I’m explaining why I’m asking this.
This question can be a little weird I know, but I’m working in a project, which is developing a compiler that takes some language as input and then compile to C.
For example, this is my language, let’s call ‘stackoverflow’ 😉
proc printInteger(integer k)
integer i;
begin
for i = 1 to k do
print i;
end
proc main()
integer n, i;
boolean ok;
begin
printInteger(getInteger);
n = getInteger;
ok = true;
while i < n do
begin
print i;
i = i + 1;
end
if ok then print 1; else print 0;
end
I won’t get deeper in the language, but notice that getInteger means that I would like to do a scanf(...), what I mean is, when appears getInteger I would like to compile as scanf(...), so that’s why I would like to know some ways to use scanf(...).
You can use
scanfas an argument to a function, but the real answer to both questions is no:scanfdoesn’t return any data scanned, it returns the number of items successfully scanned – orEOFif the end-of-input is reached before any successful scanning. You only get access to the items scanned using the pointers that you pass asscanfarguments to receive the values. So while you can passscanfas an argument to a function, it won’t do what you seem to want.If you want to implement the
getIntegeroperation in your language, in C, it’s hard to make suggestions since only you know how this language/operation should work. Just usingscanf, the implementation would look something like this:But if you’re doing general parsing for your language, then using
scanfis a bad idea: you’ll soon run into problems with the limitations ofscanf, and you’re not going to be able to anticipate all of the input types unless your language is really simple, simpler than the example that you’ve included.To do this properly, find a good
lexlibrary for C. This will prevent a lot of headaches. Otherwise, if you must do the lexing yourself, start looking overfgets, get a line at a time from your input, and do the tokenizing yourself.