PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label declaration. Show all posts
Showing posts with label declaration. Show all posts

Friday, November 4, 2022

[FIXED] how to add lambda function or perform custom operation in STL set in c++

 November 04, 2022     c++, declaration, lambda, set, stl     No comments   

Issue

I need a set arranges the value in such a way that if the int values are different i need the lexographically greater string to come front else i want the smaller integer to come front

set<pair<int,string>,[&](auto &a,auto &b){
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}>;

Solution

It seems you mean the following

#include <iostream>
#include <string>
#include <utility>
#include <set>
#include <tuple>


int main()
{
    auto less = []( const auto &p1, const auto &p2 )
    {
        return std::tie( p1.first, p2.second ) < 
               std::tie( p2.first, p1.second );
    };
    std::set<std::pair<int, std::string>, decltype( less )> 
    s( { { 1, "A" }, { 1, "B" }, { 2, "A" } }, less );

    for ( const auto &p : s )
    {
        std::cout << p.first << ' ' << p.second << '\n';
    }
}

The program output is

1 B
1 A
2 A

You could use also the constructor without the initializer list

    std::set<std::pair<int, std::string>, decltype( less )> 
    s( less );


Answered By - Vlad from Moscow
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 17, 2022

[FIXED] Why is there not any warning on a declaration without initialization in a for loop?

 July 17, 2022     c++, declaration, g++, initialization, warnings     No comments   

Issue

I tried to compile the following code using g++ (gcc version 4.8.2 (Debian 4.8.2-1)), with -Wall flag (adding the -Wextra flag does not change anything for me).

#include <iostream>

using namespace std ;

int main() {
    int i ;
    cout << i << endl ;
}

It gave this warning:

test.cpp: In function ‘int main()’:
test.cpp:7:13: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
    cout << i << endl ;

But the following code does not yield any warning:

#include <iostream>

using namespace std ;

int main() {
    for(int i ; i < 10 ; i++) {
        cout << i << endl ;
    }
}

I did further tests.

The following yields the warning:

#include <iostream>

using namespace std ;

int main() {
    int i ;
    while(i<10) {
        cout << i << endl ;
    }
}

But the following does not:

#include <iostream>

using namespace std ;

int main() {
    int i ;
    while(i<10) {
        cout << i << endl ;
        i++ ;
    }
}

In the above program, if I replace the while by an if, then I have a warning.

Is there some explanation to this? Why can the compiler recognize the problem in some cases and not in others, although they seem very close?


Solution

Thanks to Pradhan who gave this link, I understood the problem.

This link states the following:

GCC has the ability to warn the user about using the value of a uninitialized variable. Such value is undefined and it is never useful. It is not even useful as a random value, since it rarely is a random value. Unfortunately, detecting when the use of an uninitialized variable is equivalent, in the general case, to solving the halting problem. GCC tries to detect some instances by using the information gathered by optimisers and warns about them when the option -Wuninitialized is given in the command line. There are a number of perceived shortcomings in current implementation. First, it only works when optimisation is enabled through -O1, -O2 or -O3. Second, the set of false positives or negatives varies according to the optimisations enabled. This also causes high variability of the warnings reported when optimisations are added or modified between releases.

Indeed, when I add one of these flags, the compiler yields the warning.



Answered By - Tom Cornebize
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to re-declare a variable in the same scope in perl?

 July 17, 2022     declaration, perl, scope, variable-declaration, warnings     No comments   

Issue

Is there a way to re-declare a variable in the same scope using the my keyword in perl? When I run the following script:

use warnings;
use strict;

my $var = 3;
print "$var\n";

undef $var;
my $var = 4;
print "$var\n";

I get the "desired" output, but there is also a warning "my" variable $var masks earlier declaration in same scope. Is there a way to re-declare the variable without getting the warning?

I'm not sure, but I think this is because my happens at compile-time and undef happens at run-time because the warning is being printed even before the first print statement. (I'm not even sure if perl actually compiles the thing before running it.)

Context: I want to be able to copy a chunk of code and paste it multiple times in the same file without having to edit-out all the my declarations. I guess this isn't the best way to do it, but any solution to the problem would be appreciated.


Solution

To avoid the warning, you can enclose the new variable declaration, and the code that uses it, inside curly braces ({...}) and create a new scope.

my $var = 3;
print "$var\n";

{    
    my $var = 4;
    print "$var\n";
}


Answered By - mob
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 9, 2022

[FIXED] What does "default" mean after a class' function declaration?

 July 09, 2022     c++, c++11, declaration, default, keyword     No comments   

Issue

I've seen default used next to function declarations in a class. What does it do?

class C {
  C(const C&) = default;
  C(C&&) = default;
  C& operator=(const C&) & = default;
  C& operator=(C&&) & = default;
  virtual ~C() { }
};

Solution

It's a new C++11 feature.

It means that you want to use the compiler-generated version of that function, so you don't need to specify a body.

You can also use = delete to specify that you don't want the compiler to generate that function automatically.

With the introduction of move constructors and move assignment operators, the rules for when automatic versions of constructors, destructors and assignment operators are generated has become quite complex. Using = default and = delete makes things easier as you don't need to remember the rules: you just say what you want to happen.



Answered By - Peter Alexander
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 7, 2022

[FIXED] Why isn't the derived class destructor being called?

 July 07, 2022     c++, class, declaration, destructor, inheritance     No comments   

Issue

I was doing some practicing with pointers to derived classes and when I ran the code provided underneath,the output I get is

Constructor A
Constructor B
Destructor A

Could someone tell me why is B::~B() not getting invoked here?

class A {
 public:
  A() { std::cout << "Constructor A\n"; }
  ~A() { std::cout << "Destructor A\n"; }
};

class B : public A {
 public:
  B() { std::cout << "Constructor B\n"; }
  ~B() { std::cout << "Destructor B\n"; }
};

int main() {
  A* a = new B;
  delete a;
}

Solution

The static type of the pointer a is A *.

A* a = new B;

So all called member functions using this pointer are searched in the class A.

To call the destructor of the dynamic type of the pointer, that is of the class B, you need to declare the destructor as virtual in class A. For example:

#include <iostream>

class A {
 public:
  A() { std::cout << "Constructor A\n"; }
  virtual ~A() { std::cout << "Destructor A\n"; }
};

class B : public A {
 public:
  B() { std::cout << "Constructor B\n"; }
  ~B() override { std::cout << "Destructor B\n"; }
};

int main() {
  A* a = new B;
  delete a;
}


Answered By - Vlad from Moscow
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, June 26, 2022

[FIXED] Why does the compiler is giving me this: undefined reference to function?

 June 26, 2022     c, compiler-errors, declaration, function, gcc     No comments   

Issue

Ok I have been trying to figure this out for 3 hours and I have search a bunch of stack overflow questions and answers but I have this same error:

/usr/bin/ld: /tmp/ccXbXNRV.o: in function 'main':
main.c:(.text+0x5a): undefined reference to 'plus'
/usr/bin/ld: main.c:(.text+0x67): undefined reference to `minus'
collect2: error: ld returned 1 exit status

And I cant figure this out because my code doesn't seem that he is the problem

main.c:

#include <stdio.h>
#include "funcs.c"

int main()
{
    int z = 0;
    int wh = 1;
    while (wh == 1)
    {
        printf("What you want?\n1-Plus\n2-Minus\n");
        scanf("%d", &z);
        if (z == 1)
        {
            plus();
        }
        if (z == 2)
        {
            minus();
        }
    }
    printf("The program ended\n");

    return 0;
}

funcs.c

#include <stdio.h>

inline void plus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a + b;
    printf("The result is: %d\n", a);
}

inline void minus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a - b;
    printf("The result is: %d\n", a);
}

help.h

extern int a;
extern int b;
extern int z;
extern int wh;
inline void minus(void);
inline void plus(void);

I have try to compile it with this command gcc funcs.c main.c I know that is a simple program but I really want to learn c

If you could help I would be very thankful!


Solution

You can fix this by doing three things:

  1. Don't include a .c file. You're already providing it to gcc on the command line.
  2. Include help.h in files where you use those functions.
  3. Not using inline. You can't use inline when the caller and callee are in different translation units.

main.c:

#include <stdio.h>
// #include "funcs.c"
#include "help.h"

int main()
{
    int z = 0;
    int wh = 1;
    while (wh == 1)
    {
        printf("What you want?\n1-Plus\n2-Minus\n");
        scanf("%d", &z);
        if (z == 1)
        {
            plus();
        }
        if (z == 2)
        {
            minus();
        }
    }
    printf("The program ended\n");

    return 0;
}

funcs.c

#include <stdio.h>

void plus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a + b;
    printf("The result is: %d\n", a);
}

void minus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a - b;
    printf("The result is: %d\n", a);
}

help.h:

extern int a;
extern int b;
extern int z;
extern int wh;
void minus(void);
void plus(void);

Compile and run like so:

$ gcc -Wall -Werror funcs.c main.c
$ ./a.out 
What you want?
1-Plus
2-Minus
^C

Other thoughts:

extern int a;
extern int b;
extern int z;
extern int wh;

You're already declaring these variables locally. This is unneeded. The extern keyword tells the compiler that these variables are defined in another translation unit that it can't see. This isn't true, so you should just remove these.



Answered By - Nick ODell
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does my code say that it has an incomplete type even after I tried declaring it?

 June 26, 2022     c++, compiler-errors, declaration, incomplete-type, struct     No comments   

Issue

I am writing a program that displays a number of students test scores in the form of a table and then calculates and displays the average. Upon running the code, I get the following errors(also pictured below): variable has incomplete type 'struct students' struct students st[50]; ^ note: forward declaration of 'students' struct students st[50];

I have declared students and have tried declaring st and I am just not sure what the problem is. Below is a typed version and a screenshot of my code:

#include <iostream>
using namespace std;
int Main()
{
  int students;

   struct students st[50]; 
   return 0;
}

Code errors Picture of typed code


Solution

You have to define it first. You can also use this style.

struct student{
    ...
};

int main{
    student* st[50];
    for(int i=0; i<50;i++)
        st[i]=new student;
    return 0;
}


Answered By - emtsdmr
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, April 27, 2022

[FIXED] What are the implications of having an "implicit declaration of function" warning in C?

 April 27, 2022     c, declaration, function, prototype, warnings     No comments   

Issue

As the question states, what exactly are the implications of having the 'implicit declaration of function' warning? We just cranked up the warning flags on gcc and found quite a few instances of these warnings and I'm curious what type of problems this may have caused prior to fixing them?

Also, why is this a warning and not an error. How is gcc even able to successfully link this executable? As you can see in the example below, the executable functions as expected.

Take the following two files for example:

file1.c

#include <stdio.h>

int main(void)
{
   funcA();
   return 0;
}

file2.c

#include <stdio.h>

void funcA(void)
{
   puts("hello world");
}

Compile & Output

$ gcc -Wall -Wextra -c file1.c file2.c
file1.c: In function 'main':
file1.c:3: warning: implicit declaration of function 'funcA'

$ gcc -Wall -Wextra file1.o file2.o -o test.exe
$ ./test.exe
hello world

Solution

If the function has a definition that matches the implicit declaration (ie. it returns int and has a fixed number of arguments, and does not have a prototype), and you always call it with the correct number and types of arguments, then there are no negative implications (other than bad, obsolete style).

ie, in your code above, it is as if the function was declared as:

int funcA();

Since this doesn't match the function definition, the call to funcA() from file1.c invokes undefined behaviour, which means that it can crash. On your architecture, with your current compiler, it obviously doesn't - but architectures and compilers change.

GCC is able to link it because the symbol representing the function entry point doesn't change when the function type changes (again... on your current architecture, with your current compiler - although this is quite common).

Properly declaring your functions is a good thing - if for no other reason than that it allows you to give your function a prototype, which means that the compiler must diagnose it if you are calling it with the wrong number or types of arguments.



Answered By - caf
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing