V
V
vovkaooo12020-09-27 21:40:10
C++ / C#
vovkaooo1, 2020-09-27 21:40:10

How to replace a symbol in C++ using the #define directive?

I'm experimenting. If I understand correctly, #define creates a macro that allows you to substitute something anywhere in the code.
Is it possible to insert a sign into a statement with a comment?
The task is to do algebraic operations without branching.

#include <iostream>
#define Symbol symbol

int main()
{
  char symbol;
  double x, y;
  std::cin >>symbol >> x >> y;
  std::cout <<x Symbol y; //Сюда
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2020-09-27
@vovkaooo1

If you want to implement a calculator like
double res = x OPERATOR y;
AND somehow substitute the desired operation in place of OPERATOR during program execution, then no, this is not possible in C++. Write 4 if-else branches for your calculator.

A
Andrey Astafiev, 2020-09-28
@adamsgreen

In other words. Everything that starts with # is a compiler directive and will be processed during compilation. In your case, there is an attempt to construct code at a stage when the code itself has already been built and is executable. In any case, you need to validate on input and discard the "hat" from the user)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question